MATLAB: How to create a legend and include loop variable values in the labels

iterating legend numberslegend in a loop

I created the matrix P with 400 rows, 3 columns (which I call X, Y and Z).
The variables in each row are related by a simple quadratic (Y^2) and intercept term (X):
Z = Y^2 + X
And I created 10 curves, one for each unique value of X with the following code starting by isolating each unique value of X with "PU = unique…"
Please Note: This entire code only takes about 5 seconds to run:
P = [];
for X = 1:1:10
for Y = 0.1:0.1:4
Z = (Y^2) + X;
P = vertcat(P, [X, Y, Z]);
end
end
PU = unique(P(:,1));
PUC = size(PU, 1);
for i = 1:PUC;
Q{i} = P(P(:, 1) == PU(i), :);
q = Q{i};
x = PU(i);
plot(q(:, 2), q(:, 3))
legend(.......which code goes here??...)
hold on
end
hold off
Each line looks the same, and there are no labels. How do I label each line with using the variable x = PU(i) (which runs from 1 to 10) in a legend which will look like: "X = 1", "X=2", "X=3" etc… up to "X = 10", and have a changing colour or line style.
Thanks
D Howard

Best Answer

When you create a plot, you can specify the legend labels by setting the “DisplayName” property as name-value pair. Set the "DisplayName" property to a character vector of the text that you want to include in the legend. To include a variable value in the text, use “num2str”.
For example:
hold on
for k = 1:10
txt = ['X = ',num2str(k)];
plot(rand(10,1),'DisplayName',txt)
end
hold off
legend show
Starting in R2014b, plotted lines cycle through the colors in the color order.