user3818252
user3818252

Reputation:

Invoking a method defined into a running Figure

I have the following UIFigure:

classdef gui < matlab.apps.AppBase
   ...
   function app = gui
      % Construct app
   end
   ...
   properties (Access = public)
      myFuncRef = @myFun
   end
   ...
   function myFun(app)
      % do something
   end
   ...
end

in which I have defined the method myFun.

If the figure is running (that is, it's showing a window), how can I invoke the method myFun from the Command Window of MATLAB ? I tried with

h = findobj(0, 'type', 'figure');
funcRef = get(h, 'myFuncRef');
funcRef(h);

but I get the error

An error occurred while running the simulation and the simulation was terminated Caused by: Function 'subsindex' is not defined for values of class 'matlab.graphics.GraphicsPlaceholder'.

Thanks in advance!

Upvotes: 0

Views: 90

Answers (2)

Dev-iL
Dev-iL

Reputation: 24179

First I'd like to address the error you're getting. The reason for it is that the h returned by your call to findobj() is empty. Instead you should use findall(0,'Type','Figure',...) [src].

I know this is possible when the method you're referencing is static. Considering the following class:

classdef q45062561 < matlab.apps.AppBase

   properties (Access = public)
      myFuncRef = @q45062561.myFun
   end

   methods (Access = private, Static = true)
     function myFun()
        disp('This works!')
     end
   end

end

Then, running the following would yield the desired result:

>> F = q45062561;
>> F.myFuncRef()
This works!

Notes:

  1. Rather than finding the handle of the figure via findobj, I'm just storing it during creation.
  2. The modifiers of myFun are unclear from the question so I can't know if this solution is suitable in your case.
  3. Personally, I think it's a better idea to just define the method public and/or static, instead of using a function reference stored in a property.

Upvotes: 0

marco wassmer
marco wassmer

Reputation: 421

Try this one:

h = findobj(gcf,'-method','myFuncRef') 

or

h = findobj(0,'class','gui') 

let me know if it works

The probelm is probably that you get just your figure with findobj(0, 'type', 'figure'), this is just a Grahics Obejct which is manimulated by the App-Class.

Upvotes: 0

Related Questions