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

조회 수: 2 (최근 30일)
yashvin
yashvin 2015년 7월 17일
댓글: yashvin 2015년 7월 19일
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?

답변 (1개)

GT
GT 2015년 7월 17일
편집: GT 2015년 7월 17일
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
GT
GT 2015년 7월 17일
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 2015년 7월 19일
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!

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by