error reported using find function in legend

3 次查看(过去 30 天)
I'm trying to add a legend to a plot to show which line is plotted. when using find function to get the indexes of plot handles, it report error of " Index exceeds matrix dimensions." I dont know why it failed.
It works fine, if I use somethin like: legend(hp(1:Nms),get(hst(1:Nms),'string'));
Below is my code, any help is appreciated.
function gui_test
clear all;
fh = figure('Visible','on','position',[50,60, 660, 400]);
hax = axes('Units','pixels','Position',[60,90,400,300],'color','black','ylim',[-1 1]);
hpb1 = uicontrol('Style','pushbutton','String','RUN',...
'position',[500 200, 80, 40],'Callback',{@run_Callback});
hst(1)= uicontrol('style','text','string','line1',...
'units','pix','position',[500 155 55 13]);
hst(2) = uicontrol('style','text','string','line2',...
'units','pix','position',[500 135 55 13]);
hst(3) = uicontrol('style','text','string','line3',...
'units','pix','position',[500 115 55 13]);
hst(4) = uicontrol('style','text','string','line4',...
'units','pix','position',[500 95 55 13]);
c = zeros(4,3)
function run_Callback(~,~)
for i=1:4,
x=0:0.001:10;
y = 1.8*sin(i*0.2.*x).*cos(0.3.*x);
if min(y)> -1
hold all;
hp(i)= plot(x,y);
c(i,3)=1; % flag it if it is plotted
end
end
legend(hp(find(c(:,3))),get(hst((find(c(:,3))),'string')))
end
end

采纳的回答

Vivek Selvam
Vivek Selvam 2013-10-16
编辑:Vivek Selvam 2013-10-16
You had added an extra set of parenthesis:
hst((...),'string') --> hst(...),'string'
Here is the fixed line:
lh = legend(hp(find(c(:,3))),get(hst(find(c(:,3))),'string'))
set(lh,'TextColor','w') % legend text is white now
  3 个评论
Vivek Selvam
Vivek Selvam 2013-10-17
Chong Tao, here is the update you asked for:
lhKids = get(lh,'Children');
lhText = sort(lhKids(strcmp(get(lhKids,'Type'),'text')));
lineColors = get(hp(find(c(:,3))),'Color');
set(lhText,{'Color'},lineColors)
Chong Tao
Chong Tao 2013-10-17
Thanks again, Vivek. This is very helpful.

请先登录,再进行评论。

更多回答(0 个)

类别

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