-2

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

4
  • Do you want the labels to actually be "a", "b", ... and so on?
    – Matteo V
    Commented Oct 28, 2020 at 9:55
  • The best way of doing it is no doing it in a loop maner really... Just in each loop stage, store the name you want in a cell array, and then when you are finished looping , just call legend(my_legends) and thats it Commented Oct 28, 2020 at 9:58
  • Please don’t edit the answer into your question. That’s not how Stack Overflow works. Commented Oct 28, 2020 at 13:51
  • That answer explains how to solve your issue, and so do many answers in all the linked questions. I don't see what is missing, or how posting your particular bit of code adds anything useful here. /// On the other hand, if you find your own answer, you can post it as an answer in the "Your Answer" box (which is not on this page because the question is closed as a duplicate, I'm discussing general procedure). Commented Oct 28, 2020 at 14:44

1 Answer 1

4

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;
1
  • Thank you, problem solved. I had some a syntax problem in my label matrix that screwed with the 'DisplayName' . { }
    – Kwang2846
    Commented Oct 28, 2020 at 11:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.