MATLAB Answers

Legend for variable number of plots

34 views (last 30 days)
Kiran Sagar
Kiran Sagar on 9 Mar 2016
Commented: Kiran Sagar on 10 Mar 2016
Hi, I am plotting a variable 'y' whose size is 'm-by-n' against 'x' whose size is 'm-by-1'. So, I get 'n' plots on the current figure. Now, how can I write insert legend without knowing the value of n. I mean, how do I give dynamic input to legend function.
plot(x,y)
legend('Mode 1','Mode 2','Mode 3',...'Mode n')

  0 Comments

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 9 Mar 2016
legend(arrayfun(@(mode) sprintf('Mode %d', mode), 1:size(y, 2), 'UniformOutput', false))
Would be one way of doing it.

  3 Comments

Kiran Sagar
Kiran Sagar on 9 Mar 2016
Thank you very much.
Could you explain briefly, what does the syntax mean?
Guillaume
Guillaume on 9 Mar 2016
The arrayfun part builds a cell array of strings that is then passed to legend. It is equivalent to:
legendstrings = cell(1, size(y, 2)); %arrayfun automatically constructs a cell array the right size
for mode = 1:size(y, 2) %this is the second input of arrayfun
legendstrings{mode} = sprintf('Mode %d', mode); %1st input of arrayfun, sort of
end
legend(legendstrings);
Kiran Sagar
Kiran Sagar on 10 Mar 2016
Thank you very much. That was helpful

Sign in to comment.

More Answers (0)

Sign in to answer this question.