Question

I have a piece of code in which I use setappdata and then later on I call the data using getappdata which returns an empty matirx even though it is not empty. A segment of my simplified code is below:

function edit1_Callback(hObject, eventdata, handles)

C=str2double(get(hObject,'String'))
setappdata(hObject,'H',C)

% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)

if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)

N=getappdata(hObject,'H')

When I run the code I enter a value into the editbox then push the pushbutton, I get the following output

C =

     5


N =

     []

I would like the following output

C =

     5


N =

     5

I should explain that I am using getappdata and setappdata as I want to pass data between different GUI's, and I am having the empty matrix problem when doing this. So this is a very simplified problem of my final goal. I have also read a lot of different articles and the information on this problem and commands, including the mathworks site but I am pretty lost with this problem.

Was it helpful?

Solution

First, let's explain what's going on.

Within edit1_Callback, you're applying setappdata to hObject. At this point hObject refers to edit1, the editbox, and you've set its application data value H to 5.

Then you're calling getappdata within pushbutton1_Callback. At this point hObject refers to pushbutton1, and you're getting its application data value H, which has never been set, so you get [].

A previous answer has suggested that you instead use setappdata and getappdata on the root object 0. This would work, but it's basically the same as using a global variable, which is BAD.

Instead, I would suggest that you most likely want to just ensure that you're setting and getting the application data on the correct thing. Within edit1_Callback, try:

setappdata(handles.edit1,'H',C)

and within pushbutton1_Callback, try:

N=getappdata(handles.edit1, 'H')

I think that should work (it assumes that the editbox is actually called edit1, which I think is likely given your GUIDE-generated code, but change that if you've called it something else).

OTHER TIPS

You may use 0 instead of hObject. It will read/write your variable H in root workspace.

setappdata(0,'H',C);
getappdata(0,'H');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top