How to allocate legend in a for loop using figure handle?

5 views (last 30 days)
Hi My code is
x = linspace(0,3*pi)
y1 = sin(x);
y2 = sin(x - pi/4);
y3 = sin(x - pi/2);
y4 = sin(x - 3*pi/4);
y5 = sin(x - pi);
y{1}=y1
y{2}=y2
y{3}=y3
y{4}=y4
y{5}=y5
for i=1:5
h{i} = plot(x,y{i});
hold on
legend([h{i}],['X = ' num2str(i)'])
end
Using the figure handle, I want to assign each plot a corresponding text. But it is only being generated for one. I expect 5 text as i have 5 plots. What should i change?

Answers (1)

GT
GT on 17 Jul 2015
Edited: GT on 17 Jul 2015
Hi, I'd suggest following code:
x = linspace(0,3*pi);
% If you must save your results, the best way to do so is in a matrix with line i corresponding to what you % called yi
y_saved = NaN*ones(5, length(x)); % Pre allocate matrix here
% Save the legend labels in a cell
curve_legends = cell(5, 1); % Pre allocate cell here
% loop for all i
for i=0:4
% Calculate yi
y_i = sin(x - i*pi/4);
% Save it
y_saved(i+1, :) = y_i;
% Using hold is the easiest way to put several plots together
hold on
% Plot yi vs x
plot(x, y_i);
% Generate legend for curve i and save it
curve_legends{i+1} = ['X = ' num2str(i+1)];
end
% Don't need to hold anymore
hold off
% Use directly legend command on the cell, command knows what to do ;)
legend(curve_legends);
% Get y1, y2 and so on if matrix is not enough
y1 = y_saved(1, :);
y2 = y_saved(2, :);
y3 = y_saved(3, :);
y4 = y_saved(4, :);
y5 = y_saved(5, :);
You should always pre allocate a variable before using it in a loop like here you did with h. Also try to use matrices rather than cells when possible. Cells should be used mostly when you want to save strings of different lengths.
When you do h = plot, h is a reference to your axes. The axes don't change because of hold command, so h dosn't change. So here you tell him to write the legend 'X = i' on the same axes, which basically overwrites the previous one each time.
Hope this helps, Guillaume
  3 Comments
GT
GT on 17 Jul 2015
Oh I see, well if you use the figure command before each for loop, what we've done above should work fine.
What I mean:
% First plot
figure;
for loop
hold on
plot
curve_legends = ...
end for loop
hold off
legend(curve_legends)
% Second plot
figure;
for loop
hold on
plot
curve_legends2 = ...
end for loop
hold off
legend(curve_legends2)
See the code attached if you have doubts. Note that in that code I don't save each curve. I just plot it and then its not saved anymore. It's not that intricate, once you get the hang of it ;)
yashvin
yashvin on 19 Jul 2015
Thanks.
Suppose I have 5 plots each with for loop. I want to plot First plot and fourth plot on the same figure and associate a legend with it! then whats the prcodure. I want them to be on the same plot!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!