thanasissdr
thanasissdr

Reputation: 817

Plotting in MATLAB and legend

Firstly, I'm trying to figure out a much more complicated situation, but this is the most minimal example I can provide. Suppose I want to present in a common figure the graphs of the 3 functions sinx, sin(2x), sin(3x) including their legends.

I can draw the graphs in a common figure, but I have trouble with legend. I provide you my algorithm (sorry for not being an optimized one, but I 'm not much in writing algorithms).

x = 0:0.01:2*pi;
for i = 1:3
    g = plot(sin(i*x));
    legend(sprintf('sin(%f *x)', i))
    hold on
end
hold off
g

Ιt would be great if you could help me fix my algorithm.

Upvotes: 2

Views: 266

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112769

What you want can be done without loops:

  • Use bsxfun to compute the product of each i times the vector x, and then compute the sin of that. This gives you a matrix, s. Build the matrix so that each i s a different column.
  • Simply issue plot(s). When you pass a matrix to plot, a graph of each column is generated.
  • Build a cell array containing the strings (you can use arrayfun for that) and use that as the input argument to legend.

Code:

x = 0:0.01:2*pi;
ii = 1:3;
s = sin(bsxfun(@times, ii, x.'));
plot(s)
str = arrayfun(@(k) ['sin(' num2str(k) '*x)'], ii, 'uniformoutput', false);
legend(str)

Result:

enter image description here

Upvotes: 0

embert
embert

Reputation: 7612

You can pass DisplayName to the plot function

x = 0:0.01:2*pi;
for i = 1:3
    g = plot(sin(i*x),'DisplayName',sprintf('sin(%.0f *x)', i));
    hold on
end
hold off
legend('Show','Location','NorthEast')

enter image description here

Upvotes: 1

Related Questions