Write an Mfile to evaluate the equation yx x2 3x 2 for al
Write an M-file to evaluate the equation y(x) = x^2 - 3x + 2 for all values of x between -1 and 3, in steps of 0.1. Do this twice, once with a for loop and once with vectors. Plot the resulting function using a 3-point-thick dashed red line.
Solution
function y = func(n)
y = n^2 - 3*n + 2;
end
%common data
x = -1:0.1:3;
% using for loop
y1 = zeros(, 4/0.1);
j = 1;
for (i = -1 : 0.1: 3)
y1(1,j) = func(i);
j =j +1;
end
% using vector
y2 = arrayfun(@func, -1:0.1:3);
%to plot you can use:
p = plot(x, y1, \'r--\', \'Linewidth\', 3);
