Matlab GUI using GUIDE : Want to dynamically update graphs - matlab

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.

Related

Passing handles to subfunction when using `ButtonDownFcn` in Matlab gui

I need to process an image based on where the user is clicking using Matlab Gui. I have found examples which suggest to use the ButtonDownFcn like this:
function buttonSelectSuperpixels_Callback(hObject, eventdata, handles)
h = handles.myCanvas;
set(h,'ButtonDownFcn',#position_and_button);
and then process the clicked points in the subfunction position_and_button like this:
function position_and_button(hObject,eventdata)
Position = get( ancestor(hObject,'axes'), 'CurrentPoint' );
Button = get( ancestor(hObject,'figure'), 'SelectionType' );
However I would need to process some other variables in that last subfunction. Is it possible to pass the handles variable to position_and_button and also update it?
I tried to just pass handles as an argument but it doesn't seem to work.
You can pass the handles struct to your callback by adding it as an input using either an anonymous function
set(h, 'ButtonDownFcn', #(src, evnt)position_and_button(src, evnt, handles))
Or a cell array
set(h, 'ButtonDownFcn', {#position_and_button, handles})
The issue though, is that MATLAB passes variables by value rather than by reference. So when you define these callbacks, they will make a copy of handles as it looks when the callback is created. It is this copy that will be passed to the other function. Additionally, any changes that you make to handles within your callback are made to yet another copy and no other function will ever see these changes.
To avoid this behavior, you can retrieve the handles struct from the guidata within your callback (ensuring you have the most up-to-date version). Then, if you make any changes to it, you would then need to save the guidata after these changes and all other functions will be able to see these changes.
function position_and_button(src, evnt)
% Get the handles struct
handles = guidata(src);
% Now use handles struct however you want including changing variables
handles.variable2 = 2;
% Now save the changes
guidata(src, handles)
% Update the CData of the image rather than creating a new one
set(src, 'CData', newimage)
end
In this case, you would only need to specify the default two inputs to the callback function.

Matlab GUIDE - Running a script from a push button and using the workspace variables

I have a script which takes in a bunch of data and outputs a results matrix called "results".
I can get the push button to run the script, but "results" is nowhere to be found...
I have a second script which uses "results" to do further analysis, which I want the second push button in the GUI to trigger.
function pushbutton3_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton3 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
processFirstSet
processFirstSet is the first script, but it's not clear to me how to proceed from here
What comes back from your script will remain inside the GUI environment, so when the scripts ends, the pushbutton call will end and your return data "results" will be lost.
Either pass it on into the next function while staying inside the GUI and continue using the data right there (then later saving it for example) eg
function pushbutton3_Callback(hObject, eventdata, handles)
results = processFirstSet
processSecondSet(results)
%do something else
or export to the matlab workspace using assignin (eg)
function pushbutton3_Callback(hObject, eventdata, handles)
results = processFirstSet;
export_name = 'my_data';
assignin('base',export_name,results);
Here some basic hints, as I said in the comments.
Take your scrip, and turn it into a function by making a new file and using this format (replace the areas marked with your script). Save it with the same name firstStepFunction.m
function [results] = firstStepFunction(c)
a = 1; %your script here
b = 7; %your script here
results = a+b+c; %your script here
end
you can then run this function from the command line by typing firstStepFunction(2) and it will return 10 as ans into the workspace. (c) behind the function name is the function argument, if you don't need to be flexible with your function, you can leave that empty, which might be the case if you just copy past your script into the function outline.
If you now use that inside the gui pushbutton function, you need to assign the return value results (which in the example is 10) to a variable or it will get lost, for example:
results = firstStepFunction(2);
now you have results stored in a variable inside your pushbutton function. And now you can export it as above, so the whole example in this case (make sure you saved the firstStepFunction) would be
function pushbutton3_Callback(hObject, eventdata, handles)
results = firstStepFunction(2);
export_name 'my_data';
assignin('base',export_name,results);

Plotting in a nested function on matlab GUI

I am struggling to use axes on my GUI because it says it is not defined. Here is the summary of the code :
function bitirme_OpeningFcn(hObject, eventdata, handles, varargin)
axes(handles.axes1)
imshow('photo1.jpg');
...
function pushbutton1_Callback(hObject, eventdata, handles)
theta=inverseKinematic(...)
...
function [Theta1,Theta2]=inverseKinematic(angle1,angle2,angle3,desCorX,desCorY)
axes(handles.axes1);
....
plot(a,b);
....
Until the function inverseKinematic is called,everything works fine. However when it is called, the image doesn't turn to be a graphic and I see the error " Undefined variable "handles" or class "handles.axes3" " on matlab command window. Why can I not call axes(handles.axes1) in a nested function? What is the reason behind it?
Each function has its own workspace, and callbacks generated by GUIDE share data associated with what is called the handles structure. Every components of the GUI (axes, pushbuttons, etc.) are associated with the figure in which they are located. Hence GUIDE already provides the callback functions with everything stored in the handles structure.
However, nested functions do not have implicit access to the data stored in the handles structure. You need to specifically provide those data to the functions. There are a couple options available, for example:
1) Provide the handles structure as an input argument to the function.
2) Use getappdata and setappdata functions to associate data with a figure or MATLAB's root
3) Retrieve the handles structure "by hand" at the very beginning of the nested functions like so for example:
function [Theta1,Theta2]=inverseKinematic(angle1,angle2,angle3,desCorX,desCorY)
handles = guidata(gcf)
axes(handles.axes1);
....
plot(a,b);
....
%// Save the changes made to the handles structure.
guidata(handles to the figure,handles);
where gcf refers to the current figure. You can actually use the name of the figure or hObject.
Note that when using the command plot, you don't need to set the current axes before each call. You can use the Parent property inside the call to plot to select where to plot the data.
Example:
plot(a,b,'Parent',handles.axes1)
I hope that was clear enough!

Showing data on Matlab GUI which is continuously being updated in a separate Matlab function

I have a function in Matlab which is getting continuous sensor values from a hardware. It gives a flag when new values are available and we can update the variables holding these values. Following is a dummy function to mimic what this function is doing.
function example( )
% Example function to describe functionality of NatNetOptiTrack
% Hardware initialization,
% Retriving real time information continuously
for i = 1:100 %in real time this loop runs for ever
data = rand(3,6);
% Send the updated data to gui in each iteration
end
end
i have made a gui using guide as shown in the figure:
So the data to be displayed is a 3x6 matrix with columns corresponding to X Y Z Roll Pitch and Yaw values while rows correspond to Objects.
I want to show the continuously updated values from this function on the gui. Is there a way i can initialize gui inside my example function and update the output value by using the handles inside my loop. I tried copying the gui code inside the example function as a script, it was able to initialize but was not recognizing the handles.
Also i want to show the current values on command window when i press the button.
Thanks
If you launch the GUI and then run the function, you should be able to get the handles to the controls on the GUI provided that you make the GUI figure handle visible and set its tag/name to something appropriate. In GUIDE, open the Property Inspector for the GUI and set the HandleVisibility property to on, and the Tag property to MyGui (or some other name). Then in your example.m file do the following
function example( )
% Example function to describe functionality of NatNetOptiTrack
% get the handle of the GUI
hGui = findobj('Tag','MyGui');
if ~isempty(hGui)
% get the handles to the controls of the GUI
handles = guidata(hGui);
else
handles = [];
end
% Hardware initialization,
% Retriving real time information continuously
for i = 1:100 %in real time this loop runs for ever
data = rand(3,6);
% update the GUI controls
if ~isempty(handles)
% update the controls
% set(handles.yaw,…);
% etc.
end
% make sure that the GUI is refreshed with new content
drawnow();
end
end
An alternative is to copy the example function code into your GUI - the hardware initializations could occur in the _OpeningFcn of your GUI and you could create a (periodic) timer to communicate with the hardware and get the data to display on the GUI.
As for displaying the current data when pressing the GUI button, you can easily do this by writing the contents of the GUI controls to the command line/window with fprintf. You will though need to make your example function interruptible so that the push button can interrupt that continuously running loop. You can do this by either adding a pause call (for a certain number of milliseconds) that gets executed at the end of each iteration of your loop, or just make use of the drawnow call from above (that is why I placed it outside of the if statement - so that it will be called on each iteration of your loop.
Try the above and see what happens!

How to use KeyPressFCN in matlab with a function already create?

i'm in seek of information.
Me and a other students like me have to create sound in Matlab. We create them, and we have to create also an interactif interface to play those sound.
So we create a piano, and when we click on a key, it's play the sound ( that is the function. )
We also wanted that we can push a key on the Keyboard that call the function. We heard about KeyPressFCN, but we don't know how to use it, because when we search every tutorial, they didn't give enough information about it.
So, when we rightclick on the element we want, and them we call KeyPressFCN, what is the next step ? What did we have to do to "put" the function on this KeyPressFCN.
For example, to make one of the sound, we have :
% --- Execution lors d'un appui sur le bouton Do (première blanche)
function pushbutton1_Callback(hObject, eventdata, handles)
octave = str2double(get(handles.zone1,'String'));
frequence = 2093; %--- Fréquence initialement Do6
frequence2 = frequence./ octave;
son = sin(2*pi*frequence2*(0:0.000125:0.2));
sound(son);
Actually I am just quoting Matlab docs and help.
If you are using GUIDE right click on your figure (not on any object) >> View Callbacks >> KeyPressFcn, then it will auto-generate the following function:
function figure1_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure1 (see GCBO)
% eventdata structure with the following fields (see FIGURE)
% Key: name of the key that was pressed, in lower case
% Character: character interpretation of the key(s) that was pressed
% Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed
% handles structure with handles and user data (see GUIDATA)
% add this part as an experiment and see what happens!
eventdata % Let's see the KeyPress event data
disp(eventdata.Key) % Let's display the key, for fun!
Play around with your keyboard and see the eventdata. Obviously the figure must be active when you are typing.
If you are using the uicontrol (and not GUIDE) which is the programmatic way of making gui
(using Inline function)
fig_h = figure; % Open the figure and put the figure handle in fig_h
set(fig_h,'KeyPressFcn',#(fig_obj,eventDat) disp(['You just pressed: ' eventDat.Key]));
% or again use the whole eventDat.Character or eventDat.Modifier if you want.
Or if you do not want to use inline function:
fig_h = figure;
set(fig_h,'KeyPressFcn', #key_pressed_fcn);
and then define your key_pressed_fcn like: (create a new mfile with name: key_pressed_fcn.m, of course you could use whatever name you want but the same as KeyPressFcn name above)
function key_pressed_fcn(fig_obj,eventDat)
get(fig_obj, 'CurrentKey')
get(fig_obj, 'CurrentCharacter')
get(fig_obj, 'CurrentModifier')
% or
disp(eventDat)
OR! use a script as your KeyPressFcn callback function
fig_h = figure;
set(fig_h,'KeyPressFcn', 'key_pressed');
and then write key_pressed script:
get(fig_h, 'CurrentKey')
get(fig_h, 'CurrentCharacter')
get(fig_h, 'CurrentModifier')
For Matlab help refer to "KeyPressFcn Event Structure" in:
http://www.mathworks.com/help/matlab/ref/figure_props.html