Individual handles for each plot in a loop

조회 수: 3 (최근 30일)
JB
JB 2017년 9월 27일
댓글: JB 2017년 9월 28일
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
Stephen23
Stephen23 2017년 9월 28일
Option three is the best.
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