How to retrieve data from one gui to another gui in matlab? - matlab

I have two GUIs. In the first gui I want to plot an input signal (ex: sine signal). My problem is, how can I plot back the same signal in the second GUI after I clicked the 'load' pushbutton in the second GUI? Can somebody help me? I really need help.

Here is some code to get you going about using setappdata and getappdata. This is very basic and there are things which I did not mention (eg using the handles structure or passing variables as input arguments to functions) but using setappdata and getappdata is a safe way to go.
I created 2 programmatic GUIs. The code looks a bit different than when GUIs are designed with GUIDE, but the principle is exactly the same. Take the time to examine it and understand what everything does; that's not too complicated.
Each GUI is composed of one pushbutton and an axes. In the 1st GUI (sine_signal) the sine wave is created and displayed. Pressing the pushbutton opens the 2nd GUI (gui_filtering) and calls setappdata. Once you press the pushbutton of that 2nd GUI, setappdata is called to fetch the data and plot it.
Here is the code for both GUIs. You can save them as .m files and press "run" in the sine_signal function.
1) sine_signal
function sine_signal
clear
clc
%// Create figure and uicontrols. Those will be created with GUIDE in your
%// case.
hFig_sine = figure('Position',[500 500 400 400],'Name','sine_signal');
axes('Position',[.1 .1 .8 .8]);
uicontrol('Style','push','Position',[10 370 120 20],'String','Open gui_filtering','Callback',#(s,e) Opengui_filt);
%// Create values and plot them.
xvalues = 1:100;
yvalues = sin(xvalues).*cos(xvalues);
plot(xvalues,yvalues);
%// Put the x and y values together in a single array.
AllValues = [xvalues;yvalues];
%// Use setappdata to associate "AllValues" with the root directory (0).
%// This way the variable is available from anywhere. You could also
%// associate the data with the GUI itself, using "hFig_sine" instead of "0".
setappdata(0,'AllValues',AllValues);
%// Callback of the pushbutton. In this case it is simply used to open the
%// 2nd GUI.
function Opengui_filt
gui_filtering
end
end
And
2) gui_filtering
function gui_filtering
%// Same as 1st GUI.
figure('Position',[1000 1000 400 400],'Name','sine_signal')
axes('Position',[.1 .1 .8 .8])
%// Pushbutton to load data
uicontrol('Style','push','Position',[10 370 100 20],'String','Load/plot data','Callback',#(s,e) LoadData);
%// Callback of the pushbutton
function LoadData
%// Use "getappdata" to retrieve the variable "AllValues".
AllValues = getappdata(0,'AllValues');
%// Plot the data
plot(AllValues(1,:),AllValues(2,:))
end
end
To show you the expected output, here are 3 screenshots obtained when:
1) You run the 1st GUI (sine signal):
2) After pressing the pushbutton to open the 2nd GUI:
3) After pressing the pushbutton of the 2nd GUI to load/display the data:
That's about it. Hope that helps!

Related

Update gramm plot matlab crashing

I have a MATLAB GUI that calls an external function to make a plot (make_ethogram_plot).
The idea would be to have an external figure that is constantly updated with the output value from the figure. Every time the data gets updated it should replot the values, it updates at ~10 Hz. I chose gramm (https://github.com/piermorel/gramm/tree/master/%40gramm) because it is really easy to make a raster plot.
This is the function that gets called. I am having issues to
1) Make it only update in the parent figure with specific name, instead of plotting in the GUI(which is the active figure).
2) Make it not crash. It would open many figures or open or close the same figure at 10 Hz until crashing.
In this configuration, it gives error because it doesn't find g after the first plot. Making g , f, and p1 globals makes it crash (opens every time it gets called)
function make_ethogram_plot(datastructure)
% if the figure doesn't exists create it
if(isempty(findobj(0, 'Name', 'My_gramm_ethogram')))
f=figure('Name', 'My_gramm_ethogram');
p1 = uipanel('Parent',f,'BackgroundColor',[1 1 1],'BorderType','none');
g = gramm('x', datastructure.final_data.frameID, 'color', categorical(datastructure.final_data.behavior));
g.geom_raster();
g.set_parent(p1);
g.draw()
else
% defining f,p1, g here (or having them global) works but crashes
% due to refresh rate
g.update()
end
end
I wrote this code to try to replicate your problem:
function animate_random_data
N = 10000;
data = [cumsum(rand(N,1)),randn(N,1)];
for ii=0:1000
% Plot the data
make_ethogram_plot(data);
drawnow
% Compute new data
data(:,1) = cumsum(rand(N,1));
data(:,2) = randn(N,1);
end
function make_ethogram_plot(data)
fig = findobj(0, 'Name', 'My_gramm_ethogram');
if(isempty(fig))
% If the figure doesn't exists create it
fig = figure('Name', 'My_gramm_ethogram');
ax = axes(fig);
plot(ax,data(:,1),data(:,2));
drawnow
set(ax,'xlimmode','manual','ylimmode','manual');
else
% If it does, update it
line = findobj(fig,'type','line');
set(line,'xdata',data(:,1));
set(line,'ydata',data(:,2));
end
Here, I followed your concept of looking for a named figure window, and creating one if it didn't exist. However, if it does exist, I simply replace the XData and YData property of the line that is already there. This is the fastest way of animating a graph, much faster than deleting the existing plot and creating a new one. After plotting, I use drawnow to update the display. I set XLimMode and YLimMode to manual to prevent re-computation of axes limits and consequent re-drawing of the axes.
The function took 17 seconds to draw all 1000 frames, meaning it's drawing about 60 frames a second. It does not (and should not) crash MATLAB.
You can limit the display rate to 20 frames/sec with drawnow limitrate. It will skip updating the display if the frames come too fast.
I don't know what the gramm/update method does, the class is too complicated to quickly see what is going on, but I dare presume it deletes the axes and creates a new plot from scratch. Not that this should crash MATLAB, it might be worth while to submit a bug report. However, you would probably want to update the figure in the more efficient way, following the method I demonstrated above.
Note that this method can be used to update any of the graphical elements in a plot. For example, I have used this method to animate images.

How to open desired figure by dialogue box in MATLAB

Is there any possible way to open the desired figures from a lot of plotted figures in MATLAB?
If it is possible with dialogue box then it will be perfect.
I have like 75 figures plotted after my code but I have closed the figures at end of loops as they are too much.
Is it possible to open just one figure by just entering values necessary for plotting figure in MATLAB at end of program?
One way to do this is the following:
1) You save the figures as .fig in a dedicated folder using the saveas command, e.g.:
saveas(gcf,['FileName_',num2str(idx),'.fig']);
where idx is the index associated with the figure number (so in 75 in the example you mentioned). For simplicity, I would save all of them in one folder.
2) You use inputdlg to create an input dialog box, where you type in the index you want. Then, you run uiopen(['FileName_',idxFromInput,'.fig']), which will display the figure. Note that the output from inputdlg is normally a string, so you don't need num2str here.
From Wikibooks: MATLAB Programming/Handle Graphics (emphasis mine):
Every time you close a figure, either by using the close function OR by hitting the 'X', you can no longer access the data, and
attempts to do so will result in an error. Closing a figure also
destroys all the handles to the axes and annotations that depended on
it.
This means that once you close your 75 figures, they are gone for good.
I would suggest saving all your figures to .fig file format, because this will allow you to open them later in MATLAB.
Take the following example:
x = linspace(0, 2*pi); % Sample data.
for i = 1:3 % Loop 3 times.
h = figure; % Create figure window and capture its handle.
plot(i*sin(x)); % Plot some data.
saveas(h, sprintf('fig%d.fig', i)); % Save figure to .fig file format.
close(h); % Delete the figure.
end
Now you can tell MATLAB to open one of the figures using the openfig function. For example, let's open the second figure fig2.fig. Go to the Command Window and type openfig('fig2') (including the .fig extension in the file name is optional).
>> openfig('fig2')
ans =
Figure (1) with properties:
Number: 1
Name: ''
Color: [0.9400 0.9400 0.9400]
Position: [520 371 560 420]
Units: 'pixels'
Show all properties

How to plot several function calls in one figure

I made a matlab-function that plots a graph. When I call the function several times, I want it to plot all the graphs in one prepared figure. But instead my code opens with every function call the prepared figure in a new window with only one Graph in it.
My function looks like this
function myfunction(x,y)
if ~exist('myfigure')
myfigure = openfig('myfigure.fig')
assignin('base', 'myfigure',myfigure)
end
figure(myfigure);
plot(x,y)
end
With the if-function I tried to prevent it from opening a new figure-window, when myfigure is allready opened. But it seems like Matlab just ignores the if-function for my surprise. Even the Assignin didn't help out. Although checking in the command window, showed that exist('myfigure') changes its value.
I really don't know why the if-function is ignored by Matlab. Have you any suggestions how to fix this
The problem here is exist cannot see the previous figure, because it's handle is deleted when the previous call to the function was ended. My suggestion is as follow:
Pass the figure handle to the function, and also return it as output:
function myfigure = myfunction(x,y,myfigure)
if nargin<3 % if you pass 2 variables or less
myfigure = figure; % create a figure
else
figure(myfigure); % otherwise use the one in handle
end
plot(x,y)
end
Here a sample code for that:
x = 0:0.01:2*pi;
myfigure = myfunction(x,sin(x)); %first call
myfunction(x,cos(x),myfigure); % second call
myfunction(x,tan(x),myfigure); % third call...
Note that you only need to get myfunction output on the first call, then you can continue using it until you delete the figure.
The function figure that you used is probably why it opens a new figure.
What you might want to do is simply get the current axes and plot in it.
So your function would look like this
function myfunction(x,y)
myaxes = gca;
plot(myaxes,x,y)
end
This would work if you only have one active figure and axes, if you have more than you mihgt want to pass the axes handle to the function.

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!

toc vector in GUI Matlab

I have created a GUI, using GUIDE. I have added pushbuttons which perform a task. The start button, plots a graph and plays a wavefile that I have assigned to it. in the start button I have added as well a 'tic'.
on the other side of the GUI is have another button, the save button. The function of that button is to save to a vector the exact time that I push the button. The code that I have used saves only the last instance, while I want to be able to see all of the elements of that vector.
handles.counter.push(handles.count + 1)
handles.sfront(size(handles.counter)) = toc
Is there a way to save all of the instances to the sfront vector?
Thank you in advance!
You have to store your handles every time before the end of callback function.
Use GUIDATA:
guidata(hObject,handles)
To add a new element to the end of a vector use:
handles.sfront(end+1) = toc;
Then call guidata(hObject,handles) to store the updated version of handles.
I can't recreate your entire GUI here, but here's an example of storing multiple toc outputs in a vector. Takes about 10 seconds to run:
tic
tocList = [];
for i = 1:5
tocList(end+1) = toc;
pause(2)
end