How to initialize a variable in a GUI?

7 ビュー (過去 30 日間)
Antonette Augustine
Antonette Augustine 2017 年 4 月 13 日
回答済み: Sindhu Priya 2017 年 4 月 17 日
For a project I'm working on, I'm trying to initialize a variable to be zero, and I want that variable to be accessible no matter what button is pressed in the GUI. The variable will count up each time a button is pushed. ex. n=0; n=n+1; The n=n+1 would be on each button making it add up to display an image. Please help ASAP!!!!

回答 (1 件)

Sindhu Priya
Sindhu Priya 2017 年 4 月 17 日
Hi Antonette,
Here is a way to do it using GUIDE.
Add the variable to 'handles' parameter of the 'OpeningFcn' of the GUIDE as shown below,
function Test_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% varargin command line arguments to Test (see VARARGIN)
% Choose default command line output for Test
handles.output = hObject;
handles.n=0;
% Update handles structure
guidata(hObject, handles);
And for the button callbacks add the code as follows and the following code increments and displays the value of 'n' in the command window when the button is clicked.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.n=handles.n+1;
disp(handles.n);
guidata(hObject,handles)
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.n=handles.n+1;
disp(handles.n);
guidata(hObject,handles)
Hope this helps you.
Regards,
Sindhu

カテゴリ

Help Center および File ExchangeMigrate GUIDE Apps についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by