How to initialize a variable in a GUI?
7 views (last 30 days)
Show older comments
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!!!!
0 Comments
Answers (1)
Sindhu Priya
on 17 Apr 2017
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
0 Comments
See Also
Categories
Find more on Migrate GUIDE Apps in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!