matlab中for循环后的图例不起作用

时间:2015-11-16 16:13:30

标签: matlab legend

我想为此m文件添加图例,但它无法正常工作

Inp=[1 2 .1 2 .2 3 .1 1.5 .5 1.6 2 2.5 3 3 3.5 3.5;
 .1 .2 .3 .3 .4 .4 .5 .5 .6 .7 .6 .7 .6 .75 .8 .55];
 Out=[1 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0;0 0 1 0 1 0 1 0 1 1 0 0 0 0 0 0;0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1];
% 1=Bomber
% 2=Fighter
figure(1); hold on
for itt=1:length(Inp)
if Out(1,itt)==1
    plot(Inp(1,itt),Inp(2,itt),'ro','MarkerFace','r','MarkerSize',10);
elseif Out(2,itt)==1
    plot(Inp(1,itt),Inp(2,itt),'k^','MarkerFace','g','MarkerSize',10);
elseif Out(3,itt)==1
    plot(Inp(1,itt),Inp(2,itt),'bs','MarkerFace','c','MarkerSize',10);
  end
end

xlim([0 4])
ylim([0 1])
h=legend('Fighter','Bomber','Other');

请帮帮我

1 个答案:

答案 0 :(得分:0)

如果将与单个图例对应的所有点绘制为单个系列,则图例(以及几乎所有内容)的效果会更好(也更快)。矢量化!

在你的例子中,它看起来像这样(这取代了循环):

mask = (Out(1,:)==1);   % mask vector getting all kind #1
plot(Inp(1,mask),Inp(2,mask),'ro','MarkerFace','r','MarkerSize',10);

mask = (Out(2,:)==1);   %  get kind #2
plot(Inp(1,mask),Inp(2,mask),'k^','MarkerFace','g','MarkerSize',10);

mask = (Out(3,:)==1);   % get kind #3
plot(Inp(1,mask),Inp(2,mask),'bs','MarkerFace','c','MarkerSize',10);

现在,图例将使用您已有的命令开始工作。

h=legend('Fighter','Bomber','Other');