Individual handles for each plot in a loop

2 ビュー (過去 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 Center および File ExchangeAnnotations についてさらに検索

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by