How can I plot graph with lines of different color each using for loop?
Show older comments
Hello,
I draw the graph v vs t using for loop and graph should include multiple line for different dt. I try to let each lines have different color and add legend, but I got same color line and legend for last loop only. Code I write is:
%initial condition
uold=0;
dt=0.01;
i=0;%count
j=1;
frhs=@(t,v) (1/1000)*(1064*t*exp(-0.95*v)-135*v^2)-9.81;
dt=[0.001, 0.005, 0.01, 0.05, 0.1, 0.3];
for j=1:length(dt)
for told=0:dt:60
i=i+1;
[unew] = RK4(told,uold,frhs,dt(j));
uold=unew;
x(i)=told;
y(i)=unew;
end
fprintf('v(60) = %f when dt = %f \n',unew,dt(j))
plot(x,y,'color',rand(1,3))
legend(sprintf('dt=%f',dt(j)))
end
xlabel('time')
ylabel('vertical velocity')
I would like to get graph which different color line with each dt and legend to show which color is which dt.
When I run the code, color is random every time I run, but all lines are same color and legend has only for dt=0.3.

Accepted Answer
More Answers (1)
Dyuman Joshi
on 22 Apr 2024
You are over-writing the figure in each iteration, thus you only get the plot for a single iteration (i.e. the last one).
Call a figure before your for loop and retain the plots using hold on -
fig = figure;
hold on
for xyz
for abc
...
...
end
end
hold off
Remove the hold after the loops are completed.
6 Comments
Szu Yu Chew
on 22 Apr 2024
Edited: Szu Yu Chew
on 22 Apr 2024
Dyuman Joshi
on 22 Apr 2024
Please share your whole code so that I can check it and reproduce the issue.
Use the paperclip button to attach.
Szu Yu Chew
on 22 Apr 2024
Dyuman Joshi
on 22 Apr 2024
Edited: Dyuman Joshi
on 22 Apr 2024
Try this -
%initial condition
uold=0;
i=0;%count
j=1;
frhs=@(t,v) (1/1000)*(1064*t*exp(-0.95*v)-135*v^2)-9.81;
dt=[0.001, 0.005, 0.01, 0.05, 0.1, 0.3];
fig=figure;
hold on
for j=1:length(dt)
vec = 0:dt(j):60;
%preallocate accordingly
x = zeros(size(vec));
y = zeros(size(vec));
for told=vec
i=i+1;
[unew] = RK4(told,uold,frhs,dt(j));
uold=unew;
x(i)=told;
y(i)=unew;
end
fprintf('v(60) = %f when dt = %f \n',unew,dt(j))
plot(x,y,'color',rand(1,3),'DisplayName',sprintf('dt=%f',dt(j)))
end
xlabel('time')
ylabel('vertical velocity')
hold off
legend()
Szu Yu Chew
on 22 Apr 2024
Dyuman Joshi
on 22 Apr 2024
Edited: Dyuman Joshi
on 22 Apr 2024
@Szu Yu Chew, I would suggest you to -
1) Not use clear() as done in the other answer and preallocate variables instead.
See - https://in.mathworks.com/help/matlab/matlab_prog/techniques-for-improving-performance.html#buwj1nn
for reference as to why.
2) Not define legend() dynamically as done in the other answer.
You can refer to the method I have used or utilize strings like this -
str = "dt" + 1:numel(dt);
legend(str);
Categories
Find more on Legend in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
