problem in creating plot from for loop
1 回表示 (過去 30 日間)
古いコメントを表示
can anyone tell me the problem in this script. i am trying to create a plot between t and vs but it is not working properly. i am new to matlab so please share your thoughts on this script
for t = 1:10
vs = 3*exp(-t/3)*sin(pi*t);
if vs>0
vl = vs;
elseif vs<=0
vl = 0;
end
end
plot(t,vs)
0 件のコメント
回答 (2 件)
Star Strider
2022 年 8 月 5 日
The value of ‘t’ is the last value in the loop, and the intermdiate values of ‘vs’ are not saved, so the result is only one value for the last value of ‘t’ and thae last value of ‘vs’ not vectors of both. The plot function plots lines between pairs of points, not points themselves (unless a marker is specified), so here nothing gets plotted.
Changing the code to save the intermediate results —
tv = 1:10;
for k = 1:numel(tv)
t = tv(k);
vs(k) = 3*exp(-t/3)*sin(pi*t);
if vs(k)>0
vl(t) = vs(k);
elseif vs(k)<=0
vl(k) = 0;
end
end
figure
plot(tv,vs,'.-')
hold on
plot(tv, vl,'.-')
hold off
grid
legend('vs','vl', 'Location','best')
.
0 件のコメント
Kevin Holly
2022 年 8 月 5 日
for t = 1:10
vs(t) = 3*exp(-t/3)*sin(pi*t); %changed vs to vs(t) so it creates a vector array instead of just replacing the value of vs with a single element value
if vs(t)>0
vl(t) = vs(t);
elseif vs<=0
vl(t) = 0;
end
end
I defined t below as a vector array as before t = 10 before plotting. I also change vs into a vector array above.
t = 1:10;
plot(t,vs)
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!