kbirk
kbirk

Reputation: 4022

'KeyPressFcn' function to return a value

I'm trying to find a way for the function I designate as my 'KeyPressFcn' to return a value.

Currently I have:

figure('KeyPressFcn', @myFunc);

Which is fine, but I need access to the value myFunc returns

Is there a way to do this?

I've been over at http://www.mathworks.com/help/matlab/ref/figure_props.html#KeyPressFcn but looking at the examples they show, I still don't get whats going on.

The example they use has:

figure('KeyPressFcn', @(obj,evt)disp(evt));

And it says it says the function is passed an event struct. So why isn't it simply:

figure('KeyPressFcn', @disp(evt));

What is the significance of the (obj,evt) terms in front of the function name?

What is evt? what is obj? what is the significance of

Upvotes: 1

Views: 4366

Answers (1)

HebeleHododo
HebeleHododo

Reputation: 3640

You cannot return a value with callback functions in MATLAB. Instead, you can use functions like setappdata. You can get the data you have set with getappdata when you need it.

You can use them like this:

function myFunc(obj, evt)
    a = 42;
    setappdata(0, 'varName', a);
end

Outside of the callback:

otherVarName = getappdata(0, 'varName');

otherVarName will have the value of 42.


obj is the object whose callback is executing. evt is eventdata. GUIDE documentation says this:

hObject — Handle of the object, e.g., the GUI component, for which the callback was triggered. For a button group SelectionChangeFcn callback, hObject is the handle of the selected radio button or toggle button.

eventdata — Sequences of events triggered by user actions such as table selections emitted by a component in the form of a MATLAB struct (or an empty matrix for components that do not generate eventdata)

Here, hObject is obj and eventdata is evt.

Let's say you have an editbox and you want to get the text the user has written. For that, you need the handle of the editbox. That's what hObject gives you.

function buttonCallback(hObject, eventdata)
    str = get(hObject, 'String');
end

Upvotes: 2

Related Questions