如何用一个变量输入图中的图例?

问题描述 投票:1回答:1

我有一个变量x,其值为

x=0:3:30;

我想输入一个传奇作为fig

我的代码就像

x = 0:3:30;
figure(1); hold on; grid on;
for i=1:length(Var)
    plot(f1(val(x)));
end
legend('input 0', 'input 3', ..........)
figure(2); hold on; grid on;
for i=1:length(Var)
    plot(f2(val(x)));
end
legend('input 0', 'input 3', ..........)
figure(3); hold on; grid on;
for i=1:length(Var)
    plot(f3(val(x)));
end
legend('input 0', 'input 3', ..........)

有没有方法可以轻松输入图例?

当我改变x,我必须改变所有lenged输入...它是如此糟糕...... :(

matlab matlab-figure legend
1个回答
2
投票

您可以创建字符串的单元格数组,并将其传递给legend。我想出了一些代码来生成你的传奇字符串。它看起来有点笨重,但它确实有效。

s = split(sprintf('input %d\n',x'),char(10));
legend(s{1:end-1})

sprintf将格式化程序'input %d\n'应用于x中的每个值。这将创建一个字符串,其中图例条目由换行符分隔('\n'等于char(10))。 split将字符串拆分为换行符。但是因为字符串以换行符结尾,所以split创建一个空字符串作为输出的最后一个元素。 s是一个单元格数组:

s =
  12×1 cell array
    'input 0'
    'input 3'
    'input 6'
    'input 9'
    'input 12'
    'input 15'
    'input 18'
    'input 21'
    'input 24'
    'input 27'
    'input 30'
    ''

s{1:end-1}返回所有字符串,但最后一个字符串。

© www.soinside.com 2019 - 2024. All rights reserved.