ENGN2219: Computing for Engineering Simulation

Sample Answers to Lab Test 2

Sample Question 1

Let x be a vector with values ranging from 0 to , in 100 equal intervals. Let y1, y2 and y3 be functions defined as follows:

  y1 = 2000 sin(x)
  y2 = 2x3 - 4x2 + 5
  y3 = 15 2x + 1

Plot the three functions y1, y2 and y3 against x, on the same graph. Give the graph an appropriate title and labels for the x and y axes. Add a boxed legend at the top left portion of the plot.

From the graph, what is the minimum value of y1 and at what value of x does this occur?

Save this script in a file named pq3.m.

pq3.m

clear;
clc;
close all;

x = linspace(0,2*pi,100);

y1 = 2000*sin(x);
y2 = 2*x.^3 - 4*x.^2 + 5;
y3 = 15 * 2.^x + 1;

plot(x,y1,x,y2,x,y3);
xlabel('x (radians)');
ylabel('y1, y2 and y3');
title('Plot of y1, y2 and y3 vs x');
legend('boxon', 'Location', 'NorthEast');
sy1 = sprintf('y1 = 2000 sin(x)');
sy2 = sprintf('  y2 = 2 x^3 - 4 x^2 + 5');
sy3 = sprintf('y3 = 15 2^x + 1');
legend(sy1,sy2,sy3);

miny1 = min(y1);
minx = x(find(y1 == miny1));

fprintf('Min y1 = %0.2f\n',miny1);
fprintf('Min x = %0.2f\n',minx);

Sample Question 2

You are given the following data, which represents the power consumed and the current in a circuit.

Power(W) Current(A)
50,000 100
200,000 200
450,000 300
800,000 400
1,250,000 500

Compute linear, quadratic and cubic fit for the data using regression techniques and plot them on three different graphs, all on the same figure. Mark the original data with red circles. Give appropriate titles and labels for the graph.

Which model best represents the data and why?

Now, use this model to find the value of the current when the power consumed is 650,000W. Print this value of the flow.

Save this file as a script called nq2.m.

nq2.m

clear;
clc;
close all;

power = [50000 200000 450000 800000 1250000];
current = [100 200 300 400 500];

rlinear = polyfit(power,current,1);
rquadratic = polyfit(power,current,2);
rcubic = polyfit(power,current,3);

newPower = linspace(50000,1250000,100);
vrlinear = polyval(rlinear, newPower);
vrquadratic = polyval(rquadratic, newPower);
vrcubic = polyval(rcubic, newPower);

subplot(3,1,1);
plot(power,current,'or',newPower,vrlinear);
xlabel('Power (W)');
ylabel('Current (A)');
title('Linear Fit');

subplot(3,1,2);
plot(power,current,'or',newPower,vrquadratic);
xlabel('Power (W)');
ylabel('Current (A)');
title('Quadratic Fit');

subplot(3,1,3);
plot(power,current,'or',newPower,vrcubic);
xlabel('Power (W)');
ylabel('Current (A)');
title('Cubic Fit');

% Cubic fit, since it fits the data best. Error is minimised.

currentEstimate = polyval(rcubic,650000);

disp(currentEstimate);

% The value is 363.55