problem in creating plot from for loop

1 visualización (últimos 30 días)
Dinesh Bisht
Dinesh Bisht el 5 de Ag. de 2022
Respondida: Star Strider el 5 de Ag. de 2022
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)

Respuestas (2)

Star Strider
Star Strider el 5 de Ag. de 2022
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 el 5 de Ag. de 2022
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)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by