error reported using find function in legend
3 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
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
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)
More Answers (0)
See Also
Categories
Find more on Legend in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!