Can I give input arguments while referencing a callback function?

22 ビュー (過去 30 日間)
Soumyatha Gavvala
Soumyatha Gavvala 2016 年 6 月 20 日
コメント済み: Soumyatha Gavvala 2016 年 6 月 20 日
I'm new to object oriented MATLAB so bear with me.
I am plotting some data from my class S, as
Plot(s.X{i},s.Y{i},s.Data{i},...
set(gcf,'Name','Data1');
filepath = s.DirPath{1,i});
set(gca,'ButtonDownFcn',@mycallback);
Now I want to give this 'filepath' as one of the input argument for my callback function. But when I try to use filepath, it doesn't recognize it.
I also tried
set(gcf,'Tag',s.DirPath{1,i});
set(gca,'ButtonDownFcn',@mycallback);
and
get('Tag');
within my callback function.
Any help?

採用された回答

Geoff Hayes
Geoff Hayes 2016 年 6 月 20 日
Soumyatha - I don't think that it is a good idea to overwrite the Tag property of your figure with
set(gcf,'Tag',s.DirPath{1,i});
This would (to my understanding) change the name of the figure and would make it difficult to reference if you needed to elsewhere in the app.
So to pass in this file path parameter, you would do something like
set(gca,'ButtonDownFcn',{@mycallback, filepath});
and your callback signature would become
function mycallback(source, eventdata, filepath)
This should work, but you have to remember that the filepath will always have the value that was set to this variable when the callback was assigned. So if this variable ever gets modified, the callback will not see the change.
An alternative, is to nest your callback within the parent function which allows the nested function to access the variables defined within its parent. For example,
function myMainFunc
% some code here
Plot(s.X{i},s.Y{i},s.Data{i},...
set(gcf,'Name','Data1');
filepath = s.DirPath{1,i});
set(gca,'ButtonDownFcn',@mycallback);
function mycallback(source, eventdata)
% some code here
% use filepath
save(filepath,....);
end
end
Try nesting your callback. That way, if filepath is changed by some other callback, then mycallback will be able to access the changed variable.
  1 件のコメント
Soumyatha Gavvala
Soumyatha Gavvala 2016 年 6 月 20 日
I have a fixed filepath that only changes on different runs. This worked for me, thanks a lot!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeInteractive Control and Callbacks についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by