Taking data from loops and the plotting them outside the loop

조회 수: 6 (최근 30일)
Austin Hernandez
Austin Hernandez 2020년 4월 27일
편집: Mehmed Saad 2020년 4월 27일
I need to plot a graph based upon the answers given (there's a prompt window before this).
In my for loop, I have an if, elseif, and else statement, which gives 3 very different values. Should I try to put all these into 1 cell array? How can I access the data of each array and then plot it?
Or, if I do this step (make a matrix and not an array) and construct a matrix for each of the 3 options. So if it were like:
h = 0:1:10
y = zeros(size(h));
v = zeros(size(h));
o = zeros(size(h));
prompts = {'enter 1'};
dlg = 'title';
hold on
for i=1:5
A = inputdlg(prompts, dlg);
Aa = str2double(A);
x = Aa(1);
if x == 1
y(i,:) = 1000*h;
m = m + 1;
plot(h,y(i,:));
elseif x == 0
v(i,:) = h+1;
u = u + 1;
plot(h,v(i,:));
else
o(i,:) = -h*5;
c = c + 1;
plot(h,o(i,:));
end
end
end
This will give 3 different matrices of the 3 different types of answers. When I used this option, this method will generate a new row in the matrix of each output. So if I'm on loop 5, and the if statement is triggered, and I triggered the same statement in the very first loop, then I'll get a matrix like:
v =
1 2 3 4 5 6 7 8 9 10 11
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
1 2 3 4 5 6 7 8 9 10 11
How can I take the data from the rows that have nonzeros and then plot them with different boundaries on the x-axis?

채택된 답변

Mehmed Saad
Mehmed Saad 2020년 4월 27일
Initialize these variables
m=1;u=1;c=1;
replace i with m,u and c in their cases
if x == 1
y(m,:) = 1000*h;
plot(h,y(m,:));
m = m + 1;
elseif x == 0
v(u,:) = h+1;
plot(h,v(u,:));
u = u + 1;
else
o(c,:) = -h*5;
plot(h,o(c,:));
c = c + 1;
end
  댓글 수: 2
Austin Hernandez
Austin Hernandez 2020년 4월 27일
Ah, thank you! So the counter of m = m + 1 is necessary to capture each entry to the loop?
Mehmed Saad
Mehmed Saad 2020년 4월 27일
편집: Mehmed Saad 2020년 4월 27일
There's another way but it is computationaly costly and not recommended
h = 0:1:10
y=[];v=y;o=[];
prompts = {'enter 1'};
dlg = 'title';
hold on
for i=1:5
A = inputdlg(prompts, dlg);
Aa = str2double(A);
x = Aa(1);
if x == 1
y = [y;1000*h];
plot(h,y(end,:));
elseif x == 0
v = [v;h+1];
plot(h,v(end,:));
else
o = [o;-h*5];
plot(h,o(end,:));
end
end
the size of y,v and o are changing in each loop iteration and is very inefficient.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

제품


릴리스

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by