Problem in legend plot in case of empty variable [ ]

조회 수: 2 (최근 30일)
Federico Giannetti
Federico Giannetti 2022년 4월 6일
댓글: Rik 2022년 4월 6일
Hello everyone, I have a problem in a legend plot. In particular, the code is:
plot(x1,y1,'b')
plot(x2,y2,'r')
plot(x3,y3,'k')
plot(x4,y4,'m')
legend ('Plot 1', 'Plot 2', 'Plot 3', 'Plot 4')
For example, if y3 = [ ], the plot of y4 will be associated to 'Plot 3'. I would like that in case of y3 = [ ] the legend skips the corresponding 'Plot 3' and associate y4 to 'Plot 4'.
Any ideas?
Thank you all

답변 (1개)

Rik
Rik 2022년 4월 6일
I am going to assume your numbered variables are just to make this example easy to understand. If not: you should consider indexing a cell array instead.
As for you question: you can set the DisplayName property.
x1=rand(10,1);y1=rand(size(x1));
x2=rand(10,1);y2=rand(size(x1));
x4=rand(10,1);y4=rand(size(x1));
x3=[];y3=[];
h{1}=plot(x1,y1,'b','DisplayName','Plot 1');
hold on
h{2}=plot(x2,y2,'r','DisplayName','Plot 2');
h{3}=plot(x3,y3,'k','DisplayName','Plot 3');
h{4}=plot(x4,y4,'m','DisplayName','Plot 4');
legend([h{:}])
  댓글 수: 2
Federico Giannetti
Federico Giannetti 2022년 4월 6일
Perfect.
Thank you! It's working.
Rik
Rik 2022년 4월 6일
You're welcome. If this solved your issue, please consider marking it as accepted answer. If not, feel free to comment with remaining issues.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by