How do I plot separate graphs in a for loop?
56 views (last 30 days)
Show older comments
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
0 Comments
Answers (1)
Dyuman Joshi
on 14 Mar 2023
Edited: Dyuman Joshi
on 14 Mar 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
%column vector transposed
for jdx=vec'
jdx
end
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
0 Comments
See Also
Categories
Find more on Line Plots in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!