MATLAB: How to add plots to a legend in a loop

incrementallyiterationlegendloopMATLABplot

I want to add plots to a legend in each iteration of a loop but if I use the "legend" function I only get a legend for the last plot I added.
How do I incrementally add plots to the same legend?

Best Answer

There are multiple ways to add legends to a plot.
1) Set the 'DisplayName' property of each plot. The 'DisplayName' is the string shown in the legend. When you create a legend MATLAB will add all elements that have set the 'DisplayName' property to the legend. Refer to the example below.
 
t = linspace(0,2*pi,100);
figure;
axes('NextPlot','add');
for freq=1:3
plot( t, cos(freq*t),'DisplayName', ['cos(' num2str(freq) 't)']);
%uncomment if you want to see change each loop
%legend('show')
%pause;
%legend('off')
end
legend('show'); %create/show legend
2) Save the plot handles and legend labels while you loop and add them all to the legend at the end.
 
t = linspace(0,2*pi,100);
figure;
axes('NextPlot','add');
n=3;
plotHandles = zeros(1,n);
plotLabels = cell(1,n);
for freq=1:n
plotHandles(freq) = plot( t, cos(freq*t) );
plotLabels{freq} = ['cos(' num2str(freq) 't)'];
end
legend(plotHandles, plotLabels);