MATLAB Answers

0

How to add a legend to a figure, but a legend that changes every iteration in a loop ?

Asked by bh dhouha on 7 Aug 2015
Latest activity Answered by Sergio Lobo on 29 Jul 2017
I have a "while" loop (while i< tmax ). What i would like to do is to add the element "curve -- i " to the legend every iteration "i". For example if "i" goes from 1 to 3, the legend will be: curve1 curve 2 curve 3. If "i" goes from 1 to 2, the legend will be only: curve1 curve 2. Is it possible to ensure this flexibility in the legend?

  0 Comments

Sign in to comment.

3 Answers

回答者: Madhav Rajan 2015 年 8 月 7 日
 採用された回答

I understand that you want to add a legend to your figure that changes at every iteration of the loop. You can use the ' drawnow ' function to draw your legend and update your figures. You can refer the example shown below. I have also included a 3 second delay between every iteration to see the legend's string changing from 'curve 1' to 'curve1 curve 2' and so on.
j = 1;
prev = '';
while j < 4
ph(j) = plot(rand(1,20));
hold on
curr = [prev sprintf('curve %d', j)];
legend(ph(j), curr);
prev = curr;
j = j+1
drawnow; % draw now function
pause(3); % Added a three second delay to show each iteration, you can modify this.
end
hold off
Hope this helps.

  1 Comment

bh dhouha 2015 年 8 月 8 日
This is axactly what i want :) thanks a lot

Sign in to comment.


回答者: Walter Roberson
2015 年 8 月 7 日

You can use sprintf() to construct the strings that you legend() . For example,
i = 0;
residue = sqrt(2);
while residue > 0.1
i = i + 1;
h(i) = plot(rand(1,20));
hold on
legend(h(i), sprintf('curve %d', i));
residue = residue - rand();
end

  1 Comment

bh dhouha 2015 年 8 月 7 日
when i ran this code it showed only the legend "crve 3" not all the legend

Sign in to comment.


回答者: Sergio Lobo 2017 年 7 月 29 日

I found this modification to work better:
j = 1;
leg = {'a', 'b', 'x'};
figure()
hold on
while j < 4
plot(rand(1,20))
curr(j) = leg(j)
legend( curr);
j = j+1;
pause(3);
end
hold off

  0 Comments

Sign in to comment.