problem in creating plot from for loop

2 ビュー (過去 30 日間)
Dinesh Bisht
Dinesh Bisht 2022 年 8 月 5 日
回答済み: Star Strider 2022 年 8 月 5 日
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)

回答 (2 件)

Star Strider
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')
.

Kevin Holly
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)

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by