【问题标题】:How to input legend in figure with one variable?如何用一个变量在图中输入图例?
【发布时间】:2018-06-13 18:38:40
【问题描述】:

我有一个变量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 时,我必须更改所有 lenged 输入...太糟糕了...:(

【问题讨论】:

    标签: matlab matlab-figure legend


    【解决方案1】:

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

    【讨论】:

    • 啊,图例函数允许单元格参数!谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2019-09-08
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多