Global variables set in GUI with no values - Matlab - matlab

I created a GUI to set parameters and use those parameters in another m-File. I know that the variables created in GUI are in a different workspace from the input variables to the m-File. For that reason, I'm trying to use global variables, but not sucesfully: the variables goes to the m-File empty.
I have a GUI which has 3 edit boxes, that the user can set parameters (0 or 1), using this code (showing the code for only one edit box):
function density_Callback(hObject, eventdata, handles)
% hObject handle to density (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of density as text
% str2double(get(hObject,'String')) returns contents of density as a double
global density
density = str2double(get(hObject, 'String'));
global Variavel_1
assignin('base', 'Variavel_1', density);
The m-File are called from a GUI BUTTON, using this code:
function calculate_Callback(hObject, eventdata, handles)
% hObject handle to calculate (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
test %m-File that uses variables set in GUI
And the m-File should use this Variavel_1 and the others from the remaining editboxes in this code (test.m):
global Variavel_1
global Variavel_2
global sum
Variavel_1
Variavel_2
sum = Variavel_1 + Variavel_2
But all I have is all those variables empty!
(I know I can put this code inside the GUI code, but that's not the real propouse because this simple m-File to sum will be much more complex, so I need the variables to go to a m-File).
Variavel_1 = []
Variavel_2 = []
Sum = []
Can anyone understand why the global variables fails?
Thanks in advance!

In auto generated OpeningFcn callback, if you're using GUIDE
You can define variables/fields in handle structure.
This is initialization part. The data used by this can be shared across all widgets on the GUI.
So, in this callback, for variable_1,variable_2, sum, etc. you can have something like following:
handles.variable_1 = 1;
handles.variable_1 = 2;
handles.sum = handles.variable_1 + handles.variable_1 = 1;
% At end update handles structure
handles.output = hObject;
guidata(hObject, handles);
In other callback, say your Button or Edit callback
you can update these values as normal like following
handles.variable_1 = 12;
handles.variable_1 = 23;
handles.sum = handles.variable_1 + handles.variable_1 = 1;
% Now, at end of callback save the change you made to the structure
guidata(hObject,handles)
To verify these values type handles at command window.
Ref :Store or retrieve GUI data for more details.
To use these variables from GUI to other script simple assign them in workspace
like assignin('base','variable_1',handles.variable_1); ,etc in any of the callback where variable_1 is getting updated.
Then, in your m-script you can directly use these variables.

I think you could just define your test function (saved in "test.m") as:
function sum = test(x, y)
sum = x + y;
And then call your test function from your calculate_CallBack function using:
sum = test(Variavel_1, Variavel_2);
Admittedly, I am not well versed in GUI programming in MATLAB, so there may be some really obvious reason for which you cannot do this, but this avoids using global variables, which often makes for cleaner code.

Related

MATLAB - passing new value of parameter from GUI into .m script

I want to make simple GUI for my script, where I can edit parameter values and running that script.
I've created example scipt and GUI with 2 buttons. I'cant put script code into GUI code, I will need to aply it on much larger script.
So, script code:
number = 10;
variable(1:10) = NaN;
for i = 1:10;
variable(i) = i * number;
end
figure
plot(variable)
Push button code, that is working fine. script is name of .m file, not function:
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)
evalin('base','script')
But I dont know what to type into edit button code If i want to change value of "number" in the script:
function edit1_Callback(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: get(hObject,'String') returns contents of edit1 as text
% str2double(get(hObject,'String')) returns contents of edit1 as a double
And last thing, sometimes when I try to plot more graphs, one figure overwrites GUI figure and I can see only buttons, but not whole GUI.
Thank you fot any help.
The hint given in the last piece of code is enough.
a = str2double(get(hObject,'String'));
This will save the input value as a double, in the callback function's stack.
In order to pass this value to the caller script's (base) stack, use assignin
assignin('base', 'number', a)

How to call a variable used in one function in another function?

I have created a matlab gui and I want to use the variable magE from the function (pushbutton1) in the function (pushbutton2).
How can I call it?
magE = matrix of 244 rows and 2000 Columns
I would be grateful for any help. Thank you!
You should be using the hObject handle to pass data between GUI functions and callbacks, it's all quite well explained in the auto-generated comments. Example taken from MATLAB documentation:
% --- Executes just before simple_gui_tab is made visible.
function my_GUIDE_GUI_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 simple_gui_tab (see VARARGIN)
% ...
% add some additional data as a new field called numberOfErrors
handles.numberOfErrors = 0;
% Save the change you made to the structure guidata(hObject,handles)
Suppose you needed to access the numberOfErrors field in a push button callback. Your callback code now looks something like this:
% --- Executes on button press in pushbutton1.
function my_GUIDE_GUI_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)
% ...
% No need to call guidata to obtain a structure;
% it is provided by GUIDE via the handles argument
handles.numberOfErrors = handles.numberOfErrors + 1;
% save the changes to the structure
guidata(hObject,handles)
One way would be to declare magE as a global variable in the main script.
Then, inside each function you should also declare it as global so that it would refer to the same global variable.
e.g.
global magE
<your_code_here>
function [] = pushbutton1()
global magE
%%<your_code_here>
end
function [] = pushbutton2()
global magE
%%<your_code_here>
end

Use external function in matlab Gui

I have a function that reads 2 files and assign them to 2 variables:
skelfile='data/name.asf'; %asf and amc files are associated,both needed for later stages
motfile='data/name.amc';
[skel,mot]=readMocap(skelfile,motfile);%the function that i need to use is the readMocap
the above code will give variables skel,mot as 1X1 structs with information both numeric and characters(contains numbers,cells,strings,aarays as struct fields).
the problem is how to use the function inside a Gui!!
i use a pusshbutton that load the 2 files and show at 2 static texts the filenames of both asf,amc files
asf,amc files are files that contain Motion Capture data for a human skeleton
where asf has informations about the skeleton and amc about a movement(frame sequence)
function pushbutton_Callback(hObject, eventdata, handles)
% hObject handle to load_MoCap (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile('*.asf', 'MoCap files');
% show name at the static texts
if isequal(filename,0)
set(handles.asf_filename, 'String', 'Please select an .asf file to continue')
else
set(handles.asf_filename, 'String', filename)
skelfile=filename;
[filename2, pathname2] = uigetfile('*.amc;*.c3d', 'MoCap files');
if isequal(filename2,0)
set(handles.amc_filename, 'String', 'Please select an .amc file to continue')
else
set(handles.amc_filename, 'String', filename2)
%the problem
============
%from here i want to run the function and have at a static text the text that
%have when i write skel in the command promt of matlab, or at least somehow
%evaluate tha skel and mot have been assigned as structs
motfile=filename;
[skel,mot]= readMocap(skelfile, motfile);
handles.skel=skel;
handles.mot=mot;
set(handles.skel_mot,'String',skel)
% skel_mot is the static text that refer above
%and i use as property type at the set command th 'string' but i don't think
%that is correct . skel variable is a 1x1 struct
end
end
guidata(hObject,handles);
I don't have anything else in my code than the default when you start a blank gui.
a)Do i have to add something (handles)at the opening function of the gui??i don't want something to start before load the files.
b)i want to use the information from the files as inputs for other function that will be called from the gui so how can i use them as inputs when i called the function inside the gui??as skel,mot or handles.skel,handles.mot??
Thank you in advance for any response.
A few things:
Yes, you need to define the fields in handles in the opening function of your GUI. You don't need any files to open, just give them empty string values or nan values as appropriate.
You need to use the guidata function to store data in handles between callback. More information here. That way you can use handles.whatever to access variables in other callbacks.
You say that skel and mot are structures. set(handles.skel_mot,'String',skel) needs skel to be a string.
Make sure any functions you call from the gui are in the path where the gui can find them.
I found a solution to my problem!
i wrote a script that does what i want.Open from a pushbutton a window to choose my files, then i call the function inside the script so i have the structs skel,mot assigned with the wanted informations. At the end , i use the handles as Molly suggested and also the command assignin for having the skel,mot at the workspace.
so:
function GUI_1_OpeningFcn(hObject, eventdata, handles, varargin)
%default comments
handles.skel=NaN;
handles.mot=NaN;
% Choose default command line output for GUI_1
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
============
more of the default Gui code
============
%pushbutton function
function load_MoCap_Callback(hObject, eventdata, handles)
% hObject handle to load_MoCap (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
%callint the script
nameofthescript;
%here skel and mot have been assigned so i put them to the handles
handles.skel=skel;
handles.mot=mot;
%with that i have them at the workspace for evaluation of what i want to do next
assignin ('base', 'skel', handles.skel);
assignin('base','mot',handles.mot);
guidata(hObject,handles);
from then i can use handles.skel and handles.mot for inputs in any other function that i want

Making universal variables in MATLAB GUI

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:
use 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
use setappdata / getappdata functions to store your variables (this is the simpler one)
learn how to use and properly update the 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 with guidata(hObject, handles); line. After this all subsequent callbacks will see the updated handles structure.
function varargout = GUIProgramWithVariables(varargin)
% Here goes some comment from GUIDE
% Begin initialization code - DO NOT EDIT
% . . . actual code skipped
% End initialization code - DO NOT EDIT
% --- Executes just before GUIProgramWithVariables is made visible.
function GUIProgramWithVariables_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 GUIProgramWithVariables (see VARARGIN)
% Choose default command line output for GUIProgramWithVariables
handles.output = hObject;
% Here your code starts. It should be at the end of OpeningFcn
% Add your fields to handles structure
handles.C1 = 1;
handles.C2 = 2;
handles.C3 = 3;
% this updates modified handles structure
% so all subsequent call-backs will see the changes
guidata(hObject, handles);
% --- Executes on button press in Button1
function Button1_Callback(hObject, eventdata, handles)
% hObject handle to BrowseButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Here we do the magic with Button1
handles.C1 = handles.C1 + 1;
% this updates modified handles structure
% so all subsequent call-backs will see the changes
guidata(hObject, handles);
% --- Executes on button press in Button2
function Button1_Callback(hObject, eventdata, handles)
% hObject handle to BrowseButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Here we do the magic with Button2
handles.C2 = handles.C2 + 1;
% this updates modified handles structure
% so all subsequent call-backs will see the changes
guidata(hObject, handles);
% --- Executes on button press in Button3
function Button3_Callback(hObject, eventdata, handles)
% hObject handle to BrowseButton (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Here we do the magic with Button3
handles.C3 = handles.C1 + handles.C2;
% this updates modified handles structure
% so all subsequent call-backs will see the changes
guidata(hObject, handles);
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, and Z 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.
global X Y Z

Matlab GUI using GUIDE : Want to dynamically update graphs

I've written a Matlab script that reads in data using a virtual COMM port in real-time. I've done a significant amount of signal processing in an mfile.
Next, I felt the need to have a compact GUI that displays the information as summary.
I only recently started digging and reading more of Matlab's built-in GUI tool, GUIDE. I've followed a few tutorials and am successfully able to get my graphs to display on my GUI after a button-press.
However, I want the GUI to update in real-time. My data vector is constantly updating (reading in data from the COMM port). I want the GUI to keep updating the graphs with the newer data, as opposed to relying on a button press for an update. Can someone please point me in the right direction for background updating?
Here is the relevant code currently for the GUI:
% --- Executes on button press in pushbutton1.
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)
global data
global time
% Time domain plot
axes(handles.timeDomainPlot);
cla;
plot (time, data);
EDIT Changed code:
% --- Executes on button press in pushbutton1.
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)
%Setting it to display something when it ends
% t = timer('TimerFcn', 'timerOn=false; disp(''Updating GUI!'')',...
t = timer(...
'TasksToExecute', 10, ... % Number of times to run the timer object
'Period', 3, ...
'TimerFcn', GUIUpdate());
%Starting the timer
start(t)
function GUIUpdate()
global data
global time
%Parameters below axes
global min
global max
% Time domain plot
axes(handles.timeDomainPlot);
cla;
plot (time, data);
%Other parameters:
set(handles.mean, 'String', mean);
set(handles.max, 'String', max);
The error that I get is:
??? Error using ==> GUI_Learning>GUIUpdate
Too many output arguments.
Error in ==>
#(hObject,eventdata)GUI_Learning('pushbutton1_Callback',hObject,eventdata,guidata(hObject))
??? Error while evaluating uicontrol Callback
Here is an example using a timer with a timerFcn callback. I made a simple GUI with 1 axes and 1 button.
In the opening function I initialize the plot and create the timer. In the start button callback I start the timer and start manipulating the data. The timer function callback the just updates the y-data of the line via its handle. Below are the relevant functions from the GUI's M-file (snipped init section and output fcn.
function testTimer_OpeningFcn(hObject, eventdata, handles, varargin)
global y x
x = 0:.1:3*pi; % Make up some data and plot
y = sin(x);
handles.plot = plot(handles.axes1,x,y);
handles.timer = timer('ExecutionMode','fixedRate',...
'Period', 0.5,...
'TimerFcn', {#GUIUpdate,handles});
handles.output = hObject;
guidata(hObject, handles);
% --- Executes on button press in startButton.
function startButton_Callback(hObject, eventdata, handles)
global y x
start(handles.timer)
for i =1:30
y = sin(x+i/10);
pause(1)
end
function GUIUpdate(obj,event,handles)
global y
set(handles.plot,'ydata',y);
You may want a Stop button to stop the timer depending on how your GUI is structured and were/how the data is updated.
Edit: Basic handles info some of this is pretty basic and you may already know it:
An individual handle to an object contains a bunch of properties that you can read with the get() function or set with the set() function. So for example maybe I wanted to change the text of the startButton for some reason in my GUI.
set(handles.startButton,'String','Something Other Than Start');
You may just want to set a break point in your code somewhere (maybe in a button press) and play around with the handles struct. Running get() commands on various objects to learn their properties.
Now the handles structure contains all of the ... umm... handles to your GUI's objects as well as any custom items that may be convenient for your to store there. Most GUI callbacks automatically get passed the handles struct so you have easy access to all parts of the GUI.
Ex. The 'startButton' callback was automatically passed handles. So I had easy access to the timer object via handles.timer.
Which brings me to sticking custom things into handles. In the opening function I added a new item to the handles structure handles.timer and handles.plot because I knew they would be useful in other callbacks (like button press and the timerFcn callback).
However, to store these things permanently you need to use the 'guidata' function. This function basically either stores the modified handles struct or retrieves a copy of handles depending on how you call it. So the following line in the opening function is storing the modified handles structure (added .timer and .plot) into the main GUI.
guidata(hObject,handles);
Basically any time you add something in handles you should have that line to make the change permanent.
Now the other method of calling it is:
handles = guidata(hObject); %hObject can be any handle who is a child of the main GUI.
This will retrieve the handles structure for the GUI.
And last handles.output = hObject is just the default output when you launch your GUI. IF you call your GUI via Matlab's command line like this h = myGUI; it should return the handle to your GUI.
You need to use a timer object. Set the callback to be the function that updates the plots.
Take a look at Making Graphs Responsive with Data Linking
and the linkdata command.
If the same variable appears in plots in multiple figures, you can
link any of the plots to the variable. You can use linked plots in
concert with Marking Up Graphs with Data Brushing, but also on their
own. Linking plots lets you
Make graphs respond to changes in variables in the base workspace or within a function
Make graphs respond when you change variables in the Variable Editor and Command Line
Modify variables through data brushing that affect different graphical representations of them at once
Create graphical "watch windows" for debugging purposes
Watch windows are useful if you program in the MATLAB language. For
example, when refining a data processing algorithm to step through
your code, you can see graphs respond to changes in variables as a
function executes statements.
I made a quick and dirty test seen below and I am not sure how this will work in a GUI verses a function but may do the trick.
Note 1: I had to add a break point in my subroutine where it modifies the global y to actually see the plot auto-update. You may need some combination of drawnow, pause, or a timer if data is getting changed rapidly.
function testLinking()
global x y
%Links failed if the global did not also exist in the base workspace
evalin('base','global x y');
x = 0:.1:3*pi; % Make up some data and plot
y = sin(x);
h = plot(x,y,'ydatasource','y','xdatasource','x');
linkdata on
testSub
function testSub()
%Test to see if a sub can make a linked global refresh
global x y
for i = 1:10
%This should automatically update the plot.
y = sin(x+i/10);
end
Edit: there may be ways around the use of globals depending on how your functions are structured ... but I don't have time to dig into it to much.
You can add a callback on the serial object that executes a plotting function. You must attach the callback to the 'BytesAvailableFcn' event on the object (see this for more details on the properties of the com object).
Essentially, when there are bytes available on the com port, you instruct matlab to run a specific function. In your case, it will be the function updating the GUI. If you need to process the incoming data first, then your callback function will first do the signal processing and then do the plotting commands.