在MATLAB和图例中绘图

时间:2015-02-07 19:37:31

标签: matlab legend

首先,我想弄清楚一个更复杂的情况,但这是我能提供的最小的例子。假设我想在一个共同的图中呈现3个函数sinx, sin(2x), sin(3x)的图形,包括它们的图例。

我可以在一个常见的图中绘制图形,但是我遇到了问题legend.我向你提供了我的算法(很抱歉不是优化的算法,但我写的算法并不多)。

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
如果你能帮助我修改我的算法,那将会很棒。

2 个答案:

答案 0 :(得分:1)

您可以将DisplayName传递给plot函数

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

答案 1 :(得分:0)

您可以在没有循环的情况下完成所需的工作:

  • 使用bsxfun计算每个i次向量x的乘积,然后计算其sin。这为您提供了一个矩阵s。构建矩阵,使每个i成为不同的
  • 只需发出plot(s)即可。将矩阵传递给plot时,会生成每个的图表。
  • 构建一个包含字符串的单元格数组(您可以使用arrayfun)并将其用作legend的输入参数。

代码:

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)

结果:

enter image description here