简体   繁体   中英

Send handles to anonymous function in matlab?

as the topic, i am trying to send in handles so that the anonymous function can interact with the rest of the GUI. However when looking at the inputs in the anonymous functions they turn up empty.

Here adding the function to GUI:

x=5;
y=3;
z=4;
set(gca,'ButtonDownFcn', @(y,z,x)mousecontroll_callback)

Inside function will react to what you click on, but it cant read y,z or x

function mousecontroll_callback(y,z,x)
...

I get this error message when running this GUI, it is called from an other GUI called otherGUI "Error using screenmode>screenmode_OutputFcn Too many input arguments.

Error in gui_mainfcn (line 265) feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);

Error in screenmode (line 42) gui_mainfcn(gui_State, varargin{:});

Error in otherGUI>fullscreen (line 1031) screenmode(image,range); Error while evaluating uimenu Callback" -However when not messing with the inputs to the anonymous function and trying to accsess them the code runs.

I dont want to use global variables anymore, anyone knows how to get this function to get the x,y,z, which later will be the handles?

Try this one:

 set(gca,'ButtonDownFcn', { @mousecontroll_callback , x,y,z} );

 ...

 function mousecontroll_callback(hObj,evt,x,y,z)

 end

The {} syntax lets Matlab know that you want to pass additional variables.


Note that x , y and z values will be frozen as part of closure context, and will be the same even if you update them. If you want to do that, you will need to find another solution such as:

  • Using guidata global data storage to transmit a struct (Like Guide does) - Most popular solution.
  • Create your own handle object that will be passed to all functions
  • Use global variable
  • Use nested functions, which is similar to using global variable

There is an error in your code, which means that it is not doing what you think it is.

x=5;
y=3;
z=4;
set(gca,'ButtonDownFcn', @(y,z,x)mousecontroll_callback)

Where you have the above code, I am guessing you expect the following command to be executed when the button is pressed:

mousecontroll_callback(3,4,5);

In actual fact, by putting the parameters immediately after the @ symbol you are in effect creating a wrapper function as below ( baz )

x=5;
y=3;
z=4;
set(gca,'ButtonDownFcn', @baz)

function foo = baz(b,c,a)
  mousecontroll_callback
end

If you instead use the following, it should work as intended:

set(gca,'ButtonDownFcn', @() mousecontroll_callback(y,z,x));

I would also suggest taking a look at the MathWorks documentation on anonymous functions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM