Clear Filters
Clear Filters

How do I plot separate graphs in a for loop?

17 views (last 30 days)
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

Answers (1)

Dyuman Joshi
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
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

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!