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

How to input legend in figure with one variable?

我有一个变量x,其值为

x=0:3:30;

我想输入图例作为

我的代码是这样的

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 时,我必须更改所有长输入...这太糟糕了...:(

您可以创建一个字符串元胞数组,并将其传递给 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} returns 除最后一个字符串外的所有字符串。