How to dynamically allocate labels to a legend?

150 views (last 30 days)
I want to dynamically assign a legend to a data set with a changing number of vectors (v_1, v_2,...,v_n) that I plot against a single vector A. The vectors v_n are stored in a cell array, T{1,n}.
Some psuedo-code would be something like,
n=5
for i=1:n
plot(A,T{1,i})
legend('X=',i) % Essentially I want something like, legend('X=1', 'X=2', 'X=3', 'X=4', 'X=5',..., 'X=n')
end
So in this example by setting the value of n to be 5, I should get 5 different plots on my graph with a legend that displays X=1 through to X=5.
Is there a way to do this?
Thank you!

Accepted Answer

KSSV
KSSV on 14 Feb 2019
n=5 ;
lgd = cell(n,1) ;
figure
hold on
for i=1:n
plot(rand(10,1)) ;
lgd{i} = strcat('X=',num2str(i)) ;
end
legend(lgd)

More Answers (1)

Steven Lord
Steven Lord on 25 Jun 2023
Rather than generating the legend strings as a separate variable and calling legend on that variable at the end, I would set the DisplayName property of each item you want to appear in the legend then use the final legend call simply to tell MATLAB "Show the legend now."
x = 0:360;
axis([0 360 -1 1])
hold on
for k = 1:5
plot(x, sind(k*x), 'DisplayName', sprintf('sin(%d*x)', k));
end
legend show

Community Treasure Hunt

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

Start Hunting!