I'm kind of new to MATLAB and I'm doing some experiments for a school project.
What I want is a GUI with 3 buttons, when you press either of the first two, it adds up to one on a variable (one variable for each button), and when you press the third button, it does something with the variables from the first two buttons.
I used "guide" and dragged and dropped the buttons, and then I modified the functions.
But I realized that my variables only exist inside the function for the button, so if I initialize them they would restart everytime I press the button, and also there is no way for my third button to know the value of the first two.
Is there a way to make this variables always present? Or pass them from a function to another?
My code it's just the automatic code generated by "guide", with a v1 = v1+1; in the first button callback function and v2 = v2+1 in the second one, and disp(v1) disp(v2) in the third.
I hope you understand what I mean, I'm not a native english speaker so...
Anyway, thanks a lot, hope it's something easy to fix.
You have several options:
global
variables as nhowe suggested.But using global variables is not a good practice: see Top 10 MATLAB code practices that make me cry, or Wikipedia article
setappdata
/getappdata
functions to store your variables (this is the simpler one)handles
structure that appears in each callback function for GUI controls created in GUIDE (this one is more complicated).Here is an example of *.m file for case #3. Most of GUIDE-generated code was removed showing only things related to your variables. Basically, you have to update the
handles
structure in each callback function that does some changes to it withguidata(hObject, handles);
line. After this all subsequent callbacks will see the updatedhandles
structure.The following is not the best practice for large complicated programs, but for something simple like what you're trying to do it sounds like global variables would be perfect. Say that
X
,Y
, andZ
are the variables you want to share between functions. Add the following at the beginning of every function that uses them, and they will all have access to the same values.