MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn moreOpportunities for recent engineering grads.

Apply Today
Asked by Harold on 1 Dec 2011

I have a program which asks for variable values of k. A function inputs these into an equation and displays a line on a graph for each value of k. How can i label each of these lines with the value of k used for each. The problem i am having is that the k values are variable and so are the amount of lines displayed on the graph, so i can't figure out how to do this for the values that are fed to the function. Any help would be much appreciated? Thanks, Scott

*No products are associated with this question.*

Answer by Michael on 1 Dec 2011

The general method would be using the legend function, to which you give a vector of the plot object handles and a series of corresponding strings. For example,

figure; hold on a1 = plot(x,y1); M1 = "Curve 1"; a2 = plot(x,y2); M2 = "Curve 2"; legend([a1,a2], [M1, M2]);

The legend makes the connection between the plot object a1 and the string M1, and uses this to generate the legend. All you must do in your loop is devise a way to generate ai and Mi for a general integer i. I don't have MATLAB open now to test it but I think there must be a way using a combination of sprintf/num2str:

sprintf('object%s',num2str(a));

Returns "object1" if a=1, "object2" if a=2, etc.,

Hope this helps, though not a complete answer. Mike

Robert Walker on 23 Jan 2014

Not to nitpick, but the commas in the legend function should be semicolons, looking like this:

figure; hold on a1 = plot(x,y1); M1 = "Curve 1"; a2 = plot(x,y2); M2 = "Curve 2"; legend([a1; a2], [M1; M2]);

Answer by Matt Tearle on 1 Dec 2011

How about overlaying text on the graph, next to the lines?

line(x,y) % or plot(x,y) with a hold on text(max(x),max(y),num2str(k))

You could play with the (x,y) location of the text. When you say "line" do you mean a straight line or, in general, a curve? The former would make calculating placement very easy; the latter would require some more cleverness, unless max or min works for you.

Harold on 1 Dec 2011

the lines are curves, and i am not fussed about the location of the text, it just has to be somewhere.

Matt Tearle on 1 Dec 2011

Great, then what I have should do the job... unless the curves all converge at the ends or something :)

## 0 Comments