Using Stair plot with a For loop and If statement for ranges
10 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
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 Commenti
Risposta accettata
Voss
il 4 Apr 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 Commenti
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
