Using Stair plot with a For loop and If statement for ranges

7 ビュー (過去 30 日間)
A. Singh
A. Singh 2022 年 4 月 4 日
回答済み: Voss 2022 年 4 月 4 日
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))

採用された回答

Voss
Voss 2022 年 4 月 4 日
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 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by