Search code examples
matlabloopslegendmatlab-figure

How to add plot labels loops in matlab


I have data that I am plotting using a for loop. I dont know how to add a label for each graph to form a legend. This data is a lot and the names will have to be added in a looped manner. Please Advise.

Here is the code:

% Data for examples sake 
q=[1;2;3;4;5;6;7;8;9;10];

a=[1;2;3;4;5;6;7;8;9;10];
b=a*2;
c=a*3;
d=a*4;

v_matrix=[a,b,c,d];

labels = ["a","b","c","d"];

%Code

[m,n]=size(v_matrix);
figure;
for i=1:1:n;
    ylabel('Velocity (m/s)');
    xlabel('Flow Rate (m^3/h)');
    plot(q,v_matrix(:,i));
    hold on;
end

The labels are generated in the same loop as the loop that generates the v_matrix.

This is what is generated:

enter image description here

This is what I want to be generated with the loop(legend was manually added with the "insert legend" button.

enter image description here


Solution

  • One way to do this would be to give the label of each line in the plot command itself using the 'DisplayName' property and then calling the legend:

    figure
    hold on
    for i = 1:10
        % char(97) = 'a', char(98) = 'b', ...
        plot(1:10,(1:10).*i,'-','DisplayName',char(96 + i));
    end
    legend;