MATLAB: How to add a legend in a for loop

for looplegendplot

How do I add a legend in a for loop?
This is my code:
for ncol = 1: 4
plot(time{i,ncol}, knee_angle{i, ncol});
hold on;
plot(subjects(i,ncol,1),y_point_begin(i,ncol),'ro');
hold on;
plot(subjects(i,ncol,2),y_point_end(i,ncol),'k*');
xlabel('Time (s)');
ylabel('Knee Angle (rad)');
end
I want that in each plot there is legend with ncol and that ro and k* are given too. So for example the first time ncol is 3, this means that my legend would be as follows: 'Knee1', 'Knee2', 'Knee3', 'Begin', 'End'. If then ncol is 4 then I want 'Knee1', 'Knee2', 'Knee3', 'Knee4', 'Begin', 'End'.
Thank you in advance!

Best Answer

The best way is probably to use the DisplayName input for plot. You would have to be a bit careful about the order in which your plots will appear in the legend. You might want to use a cell array to hold the handles and use legend([handle_array{:}]).
Just a side note: you don't need the second call to hold, as the NextPlot property will already be set to 'add'.