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 Center および File ExchangeLine Plots についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by