Taking data from loops and the plotting them outside the loop

2 次查看(过去 30 天)
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