problem in creating plot from for loop

조회 수: 14 (최근 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)

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by