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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by