MATLAB: Command “for” and “while”

forwhile loop

Hi guys, I'm new to MatLab and I would like to know how I could use the "for" and "while" command in the following problem:
Make two programs in matlab, one applying the "for" repetition structure and the other "while" structure, to plot a function y = ax ^ 2 + bx + c to x varying from -5 to 5 with a step of 0.1 in 0.1 , using the "input" function to input values of a, b and c. The program should repeat the process N times.
Thanks!

Best Answer

Start with the smallest possible problem to understand, what the loops do.
for k = 1:5
disp(k)
end
Please run this in your command window. Does this explain, what the loop does?
WHILE and FOR loops are equivalent:
k = 1;
while k <= 5
disp(k);
k = k + 1;
end
FOR loops are useful, if you know in advance how many iterations you will get. If this is not clear, use a WHILE loop:
iter = 0;
ready = false;
while ~ready
iter = iter + 1;
x = input('Type in a number: ');
if x > 5
ready = true;
end
end
Now to your code:
x=[-5:0.1:5];
for N=-5:0.1:5
y(x)=a*x.^2+b*x+c;
end
[ and ] are the Matlab operator for a concatenation. -5:0.1:5 is a vector already and you concatenate it with nothing. So x=-5:0.1:5 is sufficient already.
y(x) means the x.th element of y. Therefore x must be a positive integer, but this is not the case e.g. for -5 or -4.9 . David has explained this already. One of the solutions:
x = -5:0.1:5;
for k = 1:numel(x)
y(k) = a * x(k) .^ 2 + b * x(k) + c;
end
You can do this without a loop in Matlab also:
x = -5:0.1:5;
y = a * x .^ 2 + b * x + c;
plot(x, y);
But I assume, the idea of this homework is to learn how to use loops.
Related Question