MATLAB GUI, how can I prevent a push button from re-initializing my variables?
1 view (last 30 days)
Show older comments
I am creating a MATLAB GUI and one of the push buttons does a certain set of commands I previously defined. The commands begin with getting two values of the GUI itself (from edit texts) then initialize two matrices according to these values. To be more clear, here is my example:
p = str2double(get(handles.P,'string'));
elev=zeros(l,p);
The problem is whenever I press the push button again, elev is set to zeros again, but my goal is to modify elev every time the push button is pressed - in my example:
elev(j+1,i)= D; %j and i are for loop arguments, and D is obtained from edit text.
Is there anyway possible to prevent the push button from re-initializing my matrix to zeros? I have seen answers including "handles" but I am not that familiar with GUIDE and I am new to it, I would really appreciate a precise explanation. Thank you in advance.
Regards,
M. Ayoub
0 Comments
Answers (1)
Walter Roberson
on 17 Dec 2017
http://matlab.wikia.com/wiki/FAQ#How_can_I_share_data_between_callback_functions_in_my_GUI.28s.29.3F
If you have a handles structure passed in then you can test
if ~isfield(handles, 'elev')
p = str2double(get(handles.P,'string'));
elev=zeros(l,p);
else
elev = handles.elev;
... do the for loop changing elev
end
handles.elev = elev;
guidata(hObject, handles);
4 Comments
Jan
on 17 Dec 2017
Or in other words:
You can store a struct inside the figure, e.g. by using guidata to store it in the figure's ApplicationData property. If you are working with GUIDE, this struct is called "handles", although it can contain everything you want, not just handles of the GUI elements. The general procedure is easy:
% Get the current value of the handles struct from the figure:
handles = guidata(hObject);
When a callback is called, the 3rd input "handles" contains the current value already.
% Modify the struct:
handles.YourData = rand(1,3); % Or whatever you want
% Store the struct in the figure afterwards:
guidata(hObject, handles);
Without the last line, the modifications are lost, when the current callback is finished. "hObject" can be the object, which have triggered the current callback, because guidata() uses its parent figure automatically.
In this way guidata() is a easy way to store values in a figure to share them between callbacks.
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!