Filter löschen
Filter löschen

Taking data from loops and the plotting them outside the loop

4 Ansichten (letzte 30 Tage)
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?

Akzeptierte Antwort

Mehmed Saad
Mehmed Saad am 27 Apr. 2020
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 Kommentare
Austin Hernandez
Austin Hernandez am 27 Apr. 2020
Ah, thank you! So the counter of m = m + 1 is necessary to capture each entry to the loop?
Mehmed Saad
Mehmed Saad am 27 Apr. 2020
Bearbeitet: Mehmed Saad am 27 Apr. 2020
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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2020a

Community Treasure Hunt

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

Start Hunting!

Translated by