0

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?

cos4
  • 95
  • 1
  • 2
  • 9
  • Please provide some code that replicates the issue. It's not clear why passing the `handles` structure, either explicitly or by using the `guidata` function isn't working. As written in the documentation for `guidata`, as long as you create your own fields (e.g. `handles.mydata`) and do not overwrite the fields generated by GUIDE you should not experience an issue. – sco1 Jul 18 '14 at 14:56
  • Additionally, `guidata(hObject, handles)` is the storage syntax, not the retrieval syntax. `handles = guidata(hObject)` will retrieve the data stored by the calling object. For the parent GUIDE GUI, this is the handles structure. – sco1 Jul 18 '14 at 15:00

2 Answers2

1

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.

Olivier
  • 921
  • 10
  • 19
0

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.

cos4
  • 95
  • 1
  • 2
  • 9