Search code examples
matlabmatlab-figurelegend

How to input legend in figure with one variable?


I have a variable x, whose value is

x=0:3:30;

I want to input a legend as fig

My code is like

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', ..........)

Is there any method to input legend easily?

When I change x, I have to change all lenged inputs... its so bad... :(


Solution

  • You can create a cell array of strings, and pass that to legend. I just came up with this bit of code to generate your legend strings. It looks a little clunky, but it works.

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

    sprintf applies the formatter 'input %d\n' to each value in x. That creates a string with legend entries separated by newlines ('\n' equal to char(10)). split splits the string at the newlines. But because the string ends with a newline, split creates an empty string as the last element of the output. s is a cell array:

    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 all strings but the last one.