Difficulty plotting values from a for loop

조회 수: 1 (최근 30일)
Alexander Babayi
Alexander Babayi 2016년 10월 4일
댓글: Alexander Babayi 2016년 10월 4일
I'm attempting to create a plot from values generated in a for loop, but the values don't seem to be appearing in the plot that MATLAB generates. Here is the code:
for t = -5:1:50;
if t>=0 && t<=8;
v = 10.*t.^2 - 5.*t;
elseif t>8 && t<16;
v = 624 - 3.*t;
elseif t>=16 && t<=26;
v = 36.*t + 12.*(t - 16).^2;
elseif t>26;
v = (2136).*exp(-0.1.*(t - 26));
else
v = 0;
end
plot(t,v,'o');
end
It seems to be only plotting the last point (at t = 50) and none of the previous points, which has led me to believe that every time the file goes through the loop and reaches the line where it is supposed to plot the coordinate pair, it overwrites the previous pair with the current one, and does so until the end, thus leaving me with only the final coordinate point on the plot. I've tried putting "disp(t)" and "disp(v)" in the place of "plot(t,v,'o')", and all the corresponding values appear in the command box, but only the last one ends up being actually plotted. How can I go about changing the code so that it retains each of the "v" values as "t" goes from -5 to 50, and is able to plot the entire domain? Do I perhaps need to change the variables in the line where it plots so that they aren't simply "t" and "v"?

채택된 답변

TallBrian
TallBrian 2016년 10월 4일
Yes, your graph is redrawing each time through the loop. You can add the command
hold on;
after the plot and then the next plot will be added to the figure instead of replacing the existing figure.
  댓글 수: 1
Alexander Babayi
Alexander Babayi 2016년 10월 4일
Thank you very much for your help, that solved the problem.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by