2

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.

4

2 回答 2

3

首先,让我们解释一下发生了什么。

在 内edit1_Callback,您正在setappdata申请hObject。此时hObjectedit1的是编辑框,并且您已将其应用程序数据值设置H为 5。

然后你在getappdata里面打电话pushbutton1_Callback。此时hObject指的是pushbutton1,你得到的是它的应用数据值H,这个值从来没有被设置过,所以你得到[].

先前的答案建议您改为在根对象 0 上使用setappdatagetappdata。这将起作用,但它与使用全局变量基本相同,这是错误的。

相反,我建议您很可能只想确保您在正确的事情上设置和获取应用程序数据。在 内edit1_Callback,尝试:

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

在 内pushbutton1_Callback,尝试:

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

我认为这应该可行(它假定实际调用了编辑框edit1,我认为这可能是由于您的 GUIDE 生成的代码,但如果您将其称为其他名称,请更改它)。

于 2013-08-20T09:44:08.240 回答
2

您可以使用0代替hObject. 它将在根工作区中读取/写入您的变量 H。

setappdata(0,'H',C);
getappdata(0,'H');
于 2013-08-20T09:28:56.820 回答