MATLAB: Legend for variable number of plots

figurelegendplotplotting

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')

Best Answer

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