来自单元格的 Matlab 图例,用于使用 for 循环创建的绘图

Matlab legend from cell for plot created with for-loop

我想在 Matlab 中创建一个图例,它使用下面虚拟代码中名为标签的单元格。我已经阅读了该论坛中的手册和帖子,建议使用 legend(labels{:}) - 但它仍然只显示最后一个图例条目。 legend('show') 显示所有条目,但不具有标签中定义的正确名称。我做错了什么?

clc;
clear;
close all;
format long;

data = cell(4,2);
for number = 1:2
     data{1,number} = [1 3 5];
     data{2,number} = [4 2 9];
     data{3,number} = [2 7 3];
     data{4,number} = [7 4 2];
end

labels = cell(4,2);
for number = 1:2
    labels{1,number} = {strcat(string(number), ': legend entry 1')};
    labels{2,number} = {strcat(string(number), ': legend entry 2')};
    labels{3,number} = {strcat(string(number), ': legend entry 3')};
    labels{4,number} = {strcat(string(number), ': legend entry 4')};
end

x = 1:3;

figure;
hold on;
for i = 1:numel(data)
   plot(x, data{i},'-o','LineWidth',1.1);
end
hold off;
   legend(labels{:});
%    legend('show');
   xlim([0.5 3+0.5]);
   ylim([0 10]);
   set(gca, 'xTick', 1:3, 'yTick', 0:1:10 );
   ytickformat('percentage');
   xlabel('Scenarios');

只需这样做:

    labels{1,number} = strcat(string(number), ': legend entry 1');
    labels{2,number} = strcat(string(number), ': legend entry 2');
    labels{3,number} = strcat(string(number), ': legend entry 3');
    labels{4,number} = strcat(string(number), ': legend entry 4');

否则您将在单元格内创建单元格,并且它们必须是单元格内的字符串。

clc;
clear;
close all;
format long;

data = cell(4,2);
for number = 1:2
     data{1,number} = [1 3 5];
     data{2,number} = [4 2 9];
     data{3,number} = [2 7 3];
     data{4,number} = [7 4 2];
end

labels = cell(4,2);
for number = 1:2
    labels{1,number} = strcat(string(number), ': legend entry 1');
    labels{2,number} = strcat(string(number), ': legend entry 2');
    labels{3,number} = strcat(string(number), ': legend entry 3');
    labels{4,number} = strcat(string(number), ': legend entry 4');
end

x = 1:3;

figure;
hold on;
for i = 1:numel(data)
   plot(x, data{i},'-o','LineWidth',1.1);
end
hold off;
   legend(labels{:});
%    legend('show');
   xlim([0.5 3+0.5]);
   ylim([0 10]);
   set(gca, 'xTick', 1:3, 'yTick', 0:1:10 );
   ytickformat('percentage');
   xlabel('Scenarios');

现在是正确的。

Figure Output: