figure plot legend keep on in for loop
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
the below code is from a for loop, have three lines and i want the legend for each loop kept on in the same figure, how can i do that.
please help.
c =[1 2 3]
for c_value=1:3
figure(1)
hold on
plot(x,u(:,find(t==0.5))), grid on
xlabel(' x ');ylabel(' u '); set(gca,'YTick',(0:25:125));
set(gca,'XTick',(0:50:xmax));ylim([-10 125]);
legend([' c = ', num2str(c(c_value))],'Position',[0.77, 0.82, .1, .1]); hold all
end
0 Kommentare
Antworten (2)
Walter Roberson
am 16 Mai 2021
c =[1 2 3]
ttarg = 0.5;
for c_value=1:3
figure(1)
hold on
leg = sprintf('c = %g', c(c_value));
dist = abs(t-ttarg);
mindist = min(dist);
plot(x, u(:,find(dist == mindist)), 'displayname', leg);
grid on
xlabel(' x ');ylabel(' u '); set(gca,'YTick',(0:25:125));
set(gca,'XTick',(0:50:xmax));ylim([-10 125]);
end
legend show
You need to be careful about using == to compare floating point numbers. The value you were using, 0.5, is one of the ones that can be exactly represented as a floating point number, but if the value being compared, t, is calculated in any way, there might not be an exact match. For example if t = 0:0.01:1 then you cannot be sure that 0.5 exactly is present in t. The code I post here does not assume that the value occurs exactly, and instead looks for the closest match.
Also, you did not give us enough context to be sure that there is only one 0.5 in t, so the above code is further complicated by needing to look for multiple matches.
As an arbitrary decision, the code only considers values exactly the same difference from 0.5 as being equal for this purpose. So if you had 0.49999 and 0.50001 both in t, then it happens that the second of those two is nearer to 0.5 exactly than the first of them, so it would pick the 0.50001 . But if you had 0.5 + 1/65536 * [-1 1] then the results would be exactly the same distance from 0.5 exactly, and it would pick both of them.
Sulaymon Eshkabilov
am 16 Mai 2021
Here is the easy solution:
LB = {};
CL = 'rgb'; % Line color type
LT = '--:-'; % Line type
for ii=1:numel(c) % You can also use c instead of ii since c values are integers.
STYLE = [CL(ii) LT(ii)];
plot(x,u(:,find(t==0.5)), STYLE), hold on
LB{ii} =['c = ' num2str(c(ii))];
legend(LB{:})
end
% More efficient to put all axis labels and settings outside of the loop
xlabel(' x '); ylabel(' u '); set(gca,'YTick',(0:25:125));
set(gca,'XTick',(0:50:xmax));ylim([-10 125]);
Good luck.
3 Kommentare
Sulaymon Eshkabilov
am 17 Mai 2021
be explicit with your found issues. As is, it is not quite clear.
Siehe auch
Kategorien
Mehr zu Legend finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!