error reported using find function in legend

2 views (last 30 days)
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

Accepted Answer

Vivek Selvam
Vivek Selvam on 16 Oct 2013
Edited: Vivek Selvam on 16 Oct 2013
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 Comments
Vivek Selvam
Vivek Selvam on 17 Oct 2013
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 on 17 Oct 2013
Thanks again, Vivek. This is very helpful.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

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

Start Hunting!