Individual handles for each plot in a loop

6 views (last 30 days)
JB
JB on 27 Sep 2017
Commented: JB on 28 Sep 2017
I am preparing a GUI where I want to plot 2-30 different plots in a axes, and I want to add a number to each plot inside a loop iteration.
Here is my code which give me one handle (handles.handle_plotCD1), but I want handles.handle_plotCD1, handles.handle_plotCD2, handles.handle_plotCD3 etc:
set(handles.axes1, 'NextPlot', 'add');
for cd=1:length(plotdata)
handles.handle_plotCD1 = plot(plotdata{cd,1}(:,1),plotdata{cd,1}(:,4),'visible','off','LineWidth',2, ...
'color', [0 0 0],'linestyle', '--', 'parent', handles.axes1);
end
How do I do this???
  1 Comment
Stephen23
Stephen23 on 28 Sep 2017
Edited: Stephen23 on 28 Sep 2017
"but I want handles.handle_plotCD1, handles.handle_plotCD2, handles.handle_plotCD3"
It is much simpler to put data into an array using indexing than to create dynamic fieldnames. Rather than magically trying to force the indexing into some strings and then use them as fieldnames, why not just use that de-facto index as... a real index ?

Sign in to comment.

Accepted Answer

OCDER
OCDER on 27 Sep 2017
Edited: OCDER on 27 Sep 2017
I would avoid using handle_plotCD1, handle_plotCD2, BUT, this can be done via something call dynamic field names . Here are 4 options to choose from:
set(handles.axes1, 'NextPlot', 'add');
for cd = 1:length(plotdata)
%Option 1: use dynamic field names
handles.([handle_plotCD num2str(cd)]) = plot(plotdata{cd,1}(:,1),plotdata{cd,1}(:,4),'visible','off','LineWidth',2, ...
'color', [0 0 0],'linestyle', '--', 'parent', handles.axes1);
%Option 2: use a cell array to store handles
handles.handle_plotCD{cd} = plot(plotdata{cd,1}(:,1),plotdata{cd,1}(:,4),'visible','off','LineWidth',2, ...
'color', [0 0 0],'linestyle', '--', 'parent', handles.axes1);
%Option 3: use a graphic object array to store handles
handles.handle_plotCD(cd) = plot(plotdata{cd,1}(:,1),plotdata{cd,1}(:,4),'visible','off','LineWidth',2, ...
'color', [0 0 0],'linestyle', '--', 'parent', handles.axes1);
%Option 4: Don't store the plot handles, as you can access them via handles.axes1
%Ex1: handles_plotCD = get(handles.axes1, 'children');
%Ex2: handles_plotCD = findobj(handles.axes1, 'type', 'line');
%Make sure to use hold to save your lines, otherwise you'll replace previous handle and get deleted handle error
if cd == 1
hold(handles.axes1, 'on')
elseif cd == length(plotdata)
hold(handles.axes1, 'off');
end
end
  2 Comments
JB
JB on 28 Sep 2017
Thanks a lot Donald Lee for this great answer. I am going with option three, also pointed out by Stephen Cobeldick. Thanks guys...

Sign in to comment.

More Answers (0)

Tags

Products

Community Treasure Hunt

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

Start Hunting!