Using Stair plot with a For loop and If statement for ranges
4 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
A. Singh
el 4 de Abr. de 2022
Respondida: Voss
el 4 de Abr. de 2022
I am trying to retreive an output for a for loop in stair graph format, but when I run the code with the plot either within, or without, the loop all I ever see is an empty graph. It seems as though it's only saving the final value of 't' and 'n' either way.
clc; clear;
for t=1:1:50
n=rand;
if n>=0 && n<0.5
I(t)=0;
else
I(t)=2;
end
% stairs(t,I(t)); hold on
end
stairs(t,I(t))
0 comentarios
Respuesta aceptada
Voss
el 4 de Abr. de 2022
In each iteration of the for loop, t is a scalar. First t is 1, then 2, and so on until t is 50 in the last iteration. Now, after the loop is finished, t is still 50, so when you plot using t and I(t) you are in fact plotting only the final value of t and I.
You need to have all values of t available after the loop in order to plot correctly, so try this:
clc; clear;
t = 1:1:50; % t is a vector with 50 elements
for ii = 1:numel(t)
n=rand;
if n>=0 && n<0.5
I(ii)=0; % could just as well use I(t(ii)) here
else
I(ii)=2; % and here, since t(ii) == ii
end
end
stairs(t,I)
0 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
