Filter löschen
Filter löschen

How do I plot separate graphs in a for loop?

18 Ansichten (letzte 30 Tage)
Joseph Sikora
Joseph Sikora am 14 Mär. 2023
Bearbeitet: Dyuman Joshi am 14 Mär. 2023
Hello. I'm fairly new to matlab and I was experimenting with "for" loops today. I get the result I want, but each line is on the same graph. How do I get it to start a new graph each time so I would have three graphs with one line on it, instead of one graph with three lines?
for A=[1;2;3]
for B=[1;2;3]
t=linspace(1,3);
ans=A+B;
plot(t,ans*t)
end
end

Antworten (1)

Dyuman Joshi
Dyuman Joshi am 14 Mär. 2023
Bearbeitet: Dyuman Joshi am 14 Mär. 2023
To iterate over the values of a column vector, you need to transpose it to create a row vector and then proceed.
Otherwise, the loop index will be equal to the column vector, see below
vec=[1;2;3];
%column vector as index
for idx=vec
idx
end
idx = 3×1
1 2 3
%column vector transposed
for jdx=vec'
jdx
end
jdx = 1
jdx = 2
jdx = 3
Use figure command to create new figure window, otherwise your plot will be overwritten.
for A=[1;2;3]'
for B=[1;2;3]'
t=linspace(1,3);
ans=A+B;
figure
%Random color for each graph
color=rand(1,3);
plot(t,ans*t,'Color',color)
end
end

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by