Individual handles for each plot in a loop

2 次查看(过去 30 天)
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 个评论
Stephen23
Stephen23 2017-9-28
编辑:Stephen23 2017-9-28
"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 ?

请先登录,再进行评论。

采纳的回答

OCDER
OCDER 2017-9-27
编辑:OCDER 2017-9-27
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 个评论
JB
JB 2017-9-28
Thanks a lot Donald Lee for this great answer. I am going with option three, also pointed out by Stephen Cobeldick. Thanks guys...

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Annotations 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by