Question

I'm having several functions (defined in separate files) within a Callback in my GUI, like that:

function myFunction_Callback(hObject, eventdata, handles)
[output] = function1(input);
[output] = function2(input);
[output] = function3(input);
guidata(hObject, handles);

Now, lets say I'm defining function1, and I want to store a local variable in handles. When I do like that:

[output] = function1(input)
localVariable = [1 2 3];
handles.myVariable = localVariable;

handles.myVariable 'disappears' from handles once the function1 is completed. How to make it 'stay' in handles? Do I have to define it as an output and later store in handles like that:

[output, localVariable] = function1(input)
...
localVariable = [1 2 3];

and later

function myFunction_Callback(hObject, eventdata, handles)
[output, handles.myVariable] = function1(input);
[output] = function2(input);
[output] = function3(input);
guidata(hObject, handles);

?? I know this question sounds super stupid and might be unclear, but forgive me, I'm very confused with GUI and handles newbie :) thanks!

Was it helpful?

Solution

Yes, your general approach is OK, although there are a few things:

  • handles typically refers to a data structure that contains handles to objects. Adding other types of data to this is valid but not advisable because it's simply confusing.

  • the brackets around single outputs of functions are not necessary. Granted, it's a matter of taste and coding style, but it's something I'd recommend against; use brackets only to group things that belong together.

  • Does your input contain handles somewhere? Similarly, do the function outputs contain a modified version of handles? If no function modifies handles, there's of course no need to re-save it every time the callback is called...

So, in summary, do it something like this:

function myFunction_Callback(hObject, eventdata, handles)
    ...
    output = func1(input);  
    output = func2(output);  
    output = func3(output);
    ...
    guidata(hObject, output);  % <-- NOTE: output contains handles


function output = func1(input)
    ...
    output.handles = input.handles;
    ...
    output.localVar = [1 2 3];
    ...

OTHER TIPS

Passing data around such functions can be quite a pain.

I found it very helpful to apply object oriented programming for these causes. Especially defining your class as classdef myclass < handles. Using these you can do all kinds of cool stuff easily - such as transfering data between unrelated figures.

It is helpful to implement a singleton pattern instead of a global. I also gave an answer here showing an observer pattern.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top