make a legend display a variable input

조회 수: 7 (최근 30일)
Jacco vD
Jacco vD 2016년 7월 6일
편집: Jacco vD 2016년 7월 6일
I'm trying to add a legend in a figure where the input of the legend is variable. I want a plot which displays 4-6 conditions with a legend that displays the corresponding conditions.
The code below is only to illustrate what i want to create. The first for-loop(for plotting) is of no importance.
clc
close all
clearvars
tst = [ 12 21 14 18];
ntst = numel(tst);
for w=1:ntst
hold on
x=linspace(1,100);
y=sin(x+x*tst(w));
plot(x,y,'Color',[rand(1),rand(1),rand(1)])
end
b='';
for a=1:ntst
b=[num2str(tst(a)),' test'];
end
legend(b,'Location', 'southeast')
The actual function has a matrix that contains data for 4-6 conditions and there is no need to plot it in a loop. The text that i want to display in the legend is formatted the same as 'tst' in the code above.

답변 (1개)

Jos (10584)
Jos (10584) 2016년 7월 6일
편집: Jos (10584) 2016년 7월 6일
% an example
x = -10:10 ;
color = {'r','g','b','k'} ;
hold on ;
for k=1:4,
y = (k-2) * x + k ;
ph(k) = plot(x,y,'.-') ;
set(ph(k),'color',color{k}) ;
legendstr{k} = sprintf('%d * x + %d',[k-2 k]) ;
end
hold off
legend(ph,legendstr)
  댓글 수: 1
Jacco vD
Jacco vD 2016년 7월 6일
편집: Jacco vD 2016년 7월 6일
well, it didn't work for me, but it made me show a mistake i made using {}, i tried it before but the code was different then so THX for reminding me :)

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

카테고리

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