Using Stair plot with a For loop and If statement for ranges
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Voss
on 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 Comments
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!