cos4
cos4

Reputation: 105

MATLAB GUI: Exchange data (handles)

I have designed a MATLAB GUI by GUIDE for image analysis. I need to share data between functions so I used the guidata function and stored it in the handles-object as it is documented (http://www.mathworks.de/de/help/matlab/ref/guidata.html).

For the auto generated callback functions (which receive handles automatically) this works well, however I also want to modify the data in self-written functions and self-written callback functions (like click on image events). I tried manually passing the handles object which gives me read access to the data but no way to store it. I tried passing the object handle too, to use guidata(hObject, handles) but the object handle does not work then.

In short: I need a way to read&write data from all functions in the file. I'm looking for a more elegant way than making everything global. That would be my last resort.

Do you have any ideas?

Upvotes: 0

Views: 1341

Answers (2)

cos4
cos4

Reputation: 105

Thank you a lot! I found the error while trying to produce a reproducebable example. In my case I was using the image handle instead of the figure handle in one function because it was an image click callback and inside that function the image was redrawn so the handle wasn't valid any more. I use gcf now to obtain the figure handle and it works fine.

Upvotes: 0

Olivier
Olivier

Reputation: 921

In GUIs, you can use the function setappdata / getappdata in order to store and share data structure between functions (link to docs).

You can use the figure as the handle. For example:

appData = struct;
appData.image = someImage;
appData.title = "someTitle";

setappdata(handles.figure1,'data',appData);

Later, you pass handles to your functions, and you can retrieve your data:

function showTitle(handles)
 appData = getappdata(handles.figure1,'data');
 title = appData.title;
 newTitle = "someNewTitle";
 appData.title = newTitle;
 setappdata(handles.figure1,'data',appData);

EDIT: Just found this link, which specifies multiple strategies to share data among callbacks.

Upvotes: 1

Related Questions