Command "for" and "while"
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
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!
5 Kommentare
David Fletcher
am 28 Apr. 2021
Bearbeitet: David Fletcher
am 28 Apr. 2021
You are still misunderstanding the purpose of the loop. If we go back to your first attempt, have a look at this and see if you can see what is happening. Then try to amend your second attempt (which is a more conventional way of doing it) to do the same thing, but using i counter in your loop. And you should really take Steven Lord's advice and go through the Matlab Onramp course - it really will make things much clearer and easier.
a=input('Insira o valor de a:');
b=input('Insira o valor de b:');
c=input('Insira o valor de c:');
iterator=1;
for N=-5:0.1:5
y(iterator)=a*N^2+b*N+c;
iterator=iterator+1;
end
plot(-5:0.1:5,y)
title ('Gráfico do exercício 3')
xlabel ('x')
ylabel ('f(x)')
Akzeptierte Antwort
Jan
am 28 Apr. 2021
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.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!