matlab eventdata of uitable returned empty - matlab

I'm trying to run a GUIDE app in Matlab, but I encounter a problem: when I try to access the location of the selected cell in a ui table, the variable holding it (eventdata.Indices) quickly changes back to an empty vector.
Here's my CellSelectionCallback function:
function varargout = ChannelMatrix(varargin)
% CHANNELMATRIX MATLAB code for ChannelMatrix.fig
% CHANNELMATRIX, by itself, creates a new CHANNELMATRIX or raises the existing
% singleton*.
%
% H = CHANNELMATRIX returns the handle to a new CHANNELMATRIX or the handle to
% the existing singleton*.
%
% CHANNELMATRIX('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in CHANNELMATRIX.M with the given input arguments.
%
% CHANNELMATRIX('Property','Value',...) creates a new CHANNELMATRIX or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before ChannelMatrix_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to ChannelMatrix_OpeningFcn via varargin.
%
% *See GUI Options on GUIDEs Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help ChannelMatrix
% Last Modified by GUIDE v2.5 14-Oct-2015 17:06:14
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #ChannelMatrix_OpeningFcn, ...
'gui_OutputFcn', #ChannelMatrix_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before ChannelMatrix is made visible.
function ChannelMatrix_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 ChannelMatrix (see VARARGIN)
clc
% Choose default command line output for ChannelMatrix
handles.output = hObject;
%CONNECT TO SWITCHER
matrixes=cell(12,6,26);
setappdata(0,'matrixes',matrixes);
set(handles.listbox1,'Value',1);
setappdata(0,'index_selected',1); %force Alpha for deafult selection
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes ChannelMatrix wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = ChannelMatrix_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes when selected cell(s) is changed in uitable1.
function uitable1_CellSelectionCallback(hObject, eventdata, handles)
% hObject handle to uitable1 (see GCBO)
% eventdata structure with the following fields (see UITABLE)
% Indices: row and column indices of the cell(s) currently selecteds
% handles structure with handles and user data (see GUIDATA)
% --- Executes when selected cell(s) is changed in uitable1.
try
currow = eventdata.Indices(1);
curcol = eventdata.Indices(2);
adata=get(handles.uitable1,'Data');
if adata{currow,curcol} == 'V'
adata{currow,curcol} = '';
else
adata{currow,curcol} = 'V';
end
set(hObject,'Data',adata);
end
% --- Executes on button press in cls_ch.
function cls_ch_Callback(hObject, eventdata, handles)
% hObject handle to cls_ch (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
index_selected = getappdata(0,'index_selected'); %get the number of selected item in listbox
matrixes = getappdata(0,'matrixes'); %get current selection of measurments
table = get(handles.uitable1,'data'); %get the selected channels for this measure
for i=3:14
for j=1:6
if table{i-2,j}=='V'
matrixes{i-2,j,index_selected}='V'; %preform scan and check - add to matrixes selcted values
end
end
end
%save changes
set(handles.uitable3,'Data',matrixes(:,:,index_selected));
setappdata(0,'matrixes',matrixes);
guidata(hObject, handles);
% --- Executes on button press in opn_ch.
function opn_ch_Callback(hObject, eventdata, handles)
% hObject handle to opn_ch (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
index_selected = getappdata(0,'index_selected'); %get the number of selected item in listbox
matrixes = getappdata(0,'matrixes'); %get current selection of measurments
table = get(handles.uitable1,'data'); %get the selected channels for this measure
for i=3:14
for j=1:6
if table{i-2,j}=='V'
matrixes{i-2,j,index_selected}=''; %preform scan and check - add to matrixes selcted values
end
end
end
%save changes
set(handles.uitable3,'Data',matrixes(:,:,index_selected));
setappdata(0,'matrixes',matrixes);
guidata(hObject, handles);
% --- Executes on button press in opn_all.
function opn_all_Callback(hObject, eventdata, handles)
% hObject handle to opn_all (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
matrixes=cell(12,6,26);
setappdata(0,'matrixes',matrixes); %sets up a new matrix
set(handles.uitable1,'Data',cell(12,6));
set(handles.uitable3,'Data',cell(12,6));
set(handles.listbox1,'Value',1);
guidata(hObject, handles);
% --- Executes on button press in clr_selection_btn.
function clr_selection_btn_Callback(hObject, eventdata, handles)
% hObject handle to clr_selection_btn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.uitable1,'Data',cell(12,6));
% --- Executes on selection change in listbox1.
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
matrixes=getappdata(0,'matrixes');
index_selected=get(hObject,'Value');
setappdata(0,'index_selected',index_selected);
set(handles.uitable3,'Data',matrixes(:,:,index_selected));
set(handles.uitable1,'Data',cell(12,6));
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function listbox1_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
What's wrong here?
Thanks!

I think there is nothing anything wrong in the definition of your uitable1_CellSelectionCallback function.
I've built a simple GUI consisting of just a uitable and executing step by step the callback in debug mode this is what actually happens:
when you left-click on a cell's table, the uitable1_CellSelectionCallback is correctly called
everything goes right up to the set(hObject,'Data',adata); instruction and eventdata.Indices array contains the row and column index of the selected cell (ref. to the Function Call Stack in the following picture)
as the set(hObject,'Data',adata); function is executed, automatically a new call to uitable1_CellSelectionCallback is made by MatLab (probably somehow triggered by set. In the next picture, you can see the second (recursive) call to uitable1_CellSelectionCallback in the Function Call Stack and the white and green pair of arrows in the edit window the debug mode
since the second call is not generated by an actual user selection of a cell, the eventdata.Indices is empty therefore an error is generated when the currow = eventdata.Indices(1); is executed
So, this is why when you click on a cell, its content is correctly set to "V" or to an empty string as you expeced but, at the same time (actually, after the time MatLab needs to make second call to uitable1_CellSelectionCallback) the GUI crashes.
I do not know if this might be considered a MatLab's bug, nevertheless I did not find any way to prevent the second call to uitable1_CellSelectionCallback.
A possible solution, not so far from yours (using try-catch) could be insert the present callback code in a if block checking if isempty(eventdata.Indices) (that is to replace try with if).
This will prevent the second call be "effective" and the generation of the error, which is not avoided by using try-catch (even if does not prevent the second call to happen).
Hope this helps.

Related

Connecting MATLAB GUI to .m file

I have a m file, which chops the signal and applies filter according to the cut off frequency(Fc).
M file:
classdef Container < handle
properties
segments = struct('signal', {}, 'time', {},'ref',{}); %empty structure with correct fields
end
methods
function this = addsignal(this, signal, time,fc)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%chopping of the signals%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
interval = diff(time);
[~, locations] = findpeaks(interval,'THRESHOLD',0.7);
edges = [0; locations; numel(signal)+1];
newsegments = struct('signal', cell(numel(edges)-1, 1), 'time', cell(numel(edges)-1, 1));
%this loop works for no peaks, 1 peak and more than one peak (because of the 0 and numel+1)
for edgeidx = 1 : numel(edges) - 1
newsegments(edgeidx).signal = signal(edges(edgeidx)+1 : edges(edgeidx+1)-1);
newsegments(edgeidx).time = time(edges(edgeidx)+1 : edges(edgeidx+1)-1);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%filtering%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
f = ltiFilter.PT1(); % another class which has filters
f.Ts = mean(diff(time));
f.fc = fc; % i want to set this value from the slider%%%%%
f.zeroPhaseShift = 1;
for i = 1:length(newsegments)
newsegments(i).ref = f.eval(newsegments(i).signal,newsegments(i).signal(1)); % application of the filter.
newsegments(i).ref = newsegments(i).ref';
end
this.segments = [this.segments; newsegments];
end
end
end
I created a GUI which has a plot and a slider(for cut off frequcy) which is shown in code as f.fc
when i created the GUI, Matlab automatically created a Code for me(i must say, I din't understand that much)
GUI code:
function varargout = GUI(varargin)
% GUI MATLAB code for GUI.fig
% GUI, by itself, creates a new GUI or raises the existing
% singleton*.
%
% H = GUI returns the handle to a new GUI or the handle to
% the existing singleton*.
%
% GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI.M with the given input arguments.
%
% GUI('Property','Value',...) creates a new GUI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before GUI_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to GUI_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help GUI
% Last Modified by GUIDE v2.5 15-Jul-2016 09:37:09
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #GUI_OpeningFcn, ...
'gui_OutputFcn', #GUI_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before GUI is made visible.
function 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 GUI (see VARARGIN)
% Choose default command line output for GUI
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes GUI wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = GUI_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on slider movement.
function slider1_Callback(hObject, eventdata, handles)
% hObject handle to slider1 (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,'Value') returns position of slider
% get(hObject,'Min') and get(hObject,'Max') to determine range of slider
% --- Executes during object creation, after setting all properties.
function slider1_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: slider controls usually have a light gray background.
if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor',[.9 .9 .9]);
end
% --- 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)
% --- Executes on button press in pushbutton3.
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)
What i want to do is, i want to connect the GUI to my m script, when user sildes the slider . it should show the change in graph automatically and when he clicks on apply. the value of slider should be taken and should be available in my m file.
Any leads will be helpful.
From code sample pasted, I'm assuming you are using MATLAB GUIDE. Let's assume name of slider control is "slider1".
Add a callback function for "slider" using GUIDE.
It will create a function "function slider1_Callback(hObject, eventdata, handles)" in your code.
Now, to get value selected from slider movement use "get" function with "hObject".
E.g. SliderVal=get(hObject,'Value');
Now if you want to know value of slider selection from other callbacks (such as Apply button)
use handles structure.
E.g.: SliderVal=get(handles.slider1,'Value');
Based on slider value, received you need to re-draw plot area.
I hope this helps as clue you are expecting.
Edit1:
For followup comment, how to get data from other M-file:
This will be very tricky. Because, you need to know handle of slider control in other M-file.
One of the ways would be to get handle of figure first.
Set "HandleVisibility" property of GUI figure (via GUIDE) to "ON".
Call "figures = get(0,'Children');" from M-script to get list of all open figures. This will give vector of figure handles.
Scan through list of children and get handle of your application. (This can be done via using property get(figures(1),'Name')).
Let's assume you found that handle, repeat same process again to get children from it. get(figHandle,'Children').
Scan through children and find slider control handle similar to approach as in step 3.
Now you have access to control and it's data.
I hope you understood it.

Supply inputs to a GUI and catch the output in order to use it in another function

I have created a GUI function as follows. what I am trying to do is to put this GUI in a loop so that I can use it for different elements. for the output I have two vectors that are 6 by 1. What I am trying to do is, when I choose different radio buttons and put different values in the edit text of the GUI, to have the results saved in different positions of the output vector depending on the radio buttons. I am trying to give the GUI a title as the input.
Thanks in advance.
function varargout = distributedloads(varargin)
% DISTRIBUTEDLOADS MATLAB code for distributedloads.fig
% DISTRIBUTEDLOADS, by itself, creates a new DISTRIBUTEDLOADS or raises the existing
% singleton*.
%
% H = DISTRIBUTEDLOADS returns the handle to a new DISTRIBUTEDLOADS or the handle to
% the existing singleton*.
%
% DISTRIBUTEDLOADS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in DISTRIBUTEDLOADS.M with the given input arguments.
%
% DISTRIBUTEDLOADS('Property','Value',...) creates a new DISTRIBUTEDLOADS or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before distributedloads_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to distributedloads_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help distributedloads
% Last Modified by GUIDE v2.5 28-Feb-2016 14:52:56
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #distributedloads_OpeningFcn, ...
'gui_OutputFcn', #distributedloads_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before distributedloads is made visible.
function distributedloads_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 distributedloads (see VARARGIN)
imshow('disloads.png')
% Choose default command line output for distributedloads
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes distributedloads wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = distributedloads_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
varargout = str2double(handles.DATA.EL);
function ELNUM_Callback(hObject, eventdata, handles)
% hObject handle to ELNUM (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 ELNUM as text
% str2double(get(hObject,'String')) returns contents of ELNUM as a double
EL = get(hObject , 'String');
handles.DATA.EL = EL;
guidata(hObject,handles)
% --- Executes during object creation, after setting all properties.
function ELNUM_CreateFcn(hObject, eventdata, handles)
% hObject handle to ELNUM (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
function LOADVAL_Callback(hObject, eventdata, handles)
% hObject handle to LOADVAL (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 LOADVAL as text
% str2double(get(hObject,'String')) returns contents of LOADVAL as a double
Load = get(hObject , 'String');
handles.DATA.Load = Load;
guidata(hObject , handles)
% --- Executes during object creation, after setting all properties.
function LOADVAL_CreateFcn(hObject, eventdata, handles)
% hObject handle to LOADVAL (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in CONFIRM.
function CONFIRM_Callback(hObject, eventdata, handles)
% hObject handle to CONFIRM (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
delete(handles.figure1)
% --------------------------------------------------------------------
function buttongroup_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to buttongroup (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
Type = get(hObject , 'selectedObject');
handles.DATA.Type = Type;
guidata(hObject , handles)
I wrote an example script that creates GUI and a one callback function.
In the GUI there is vector of handles to Radio Buttons, Push Button and axes with line to visualize the results.
The script code:
close all % close all figures
figure % open a figure for GUI
Values=zeros(3,1); % Variable of the interest
UIGroup=uibuttongroup('parent',gcf,'position',[0 0 1 1]); % Group for Radio Buttons
for ii=1:3 % create 3 Radio buttons, for example
RB(ii)=uicontrol('style','radiobutton',...
'units','normalized','position',[.05, ii/10 0.15 0.1],...
'parent',UIGroup,'string',['Button ' num2str(ii)]);
end
% Push Button that runs DoIt function
uicontrol('style','pushbutton','string','DO',...
'units','normalized','position',[0.45 0.05 0.1 0.1],...
'callback','Values=DoIt(RB,L,Values);')
% Axes and Line just for example
ax=axes('units','normalized','position',[0.25 0.2 0.6 0.7],...
'xlim',[-0.1 3.1],'ylim',[-0.1 1.1]);
L=line('xdata',1:3,'ydata',Values,'marker','.','linestyle','none')
This script defines Values variable and content of the GUI.
Push Button runs the DoIt function which assigns new content to Values according to RB handle. Values are needed only to keep other values in Values, L is used only to visualize the changes.
DoIt code:
function[OutValues]=DoIt(RadioHandle,LineHandle,InValues)
OutValues=InValues; % Copy Values from input to output variable
%% Find which radio button is active
M=max(size(RadioHandle));
for ii=1:M
Radios(ii)=get(RadioHandle(ii),'value');
end
RadioChecked=find(Radios==1); % This RadioButton is active
OutValues(RadioChecked)=ProcessIt; % Process the chosen position.
set(LineHandle,'ydata',OutValues);% Visualize the change
function[OUT]=ProcessIt()
OUT=rand; % this function will just return random value, for example.
The DoIt function reads handle to radio buttons RB and determines which button is active. Then it change the appropriate value in Value variable and return it and changes y-values in line with handle L.
In this example it will assign random value to the defined point but You can pass any variable from workspace / parent function and call any function.

Matlab: set default values for GUI edit text and use them in push button callback

I'm trying to initialize a GUI (built with GUIDE) with default values and then, if the user does not change the defaults, use these values in a function triggered by a push button callback.
To do this, inside the _CreateFcn, I first store the default values within the handles, then set the default of the GUI with set(hObject, ...) and finally update the guidata with guidata(hObject, handles);
If the user changes the value, I store the updated value in the handles inside the _Callback function reading the value with get(hObject, ...) and updating the guidata with guidata(hObject, handles);
When the button is pushed, inside the button _Callback function, I extract the value from the handles.
What happen is the following:
if the user does not change the value on the GUI and simply pushes the button, what I read out from the variable stored in the handles is not the value of the variable, but the actual handle to the variable (for example: 27.0098876953125)
If, on the other hand, the user does change the value before pushing the button, then everything works fine and I get the actual variable value.
What am I missing?
Update
Following oro777 comment I've added the rest of the code for better analysis. I've also tried with a more recent (R2015b) version of MATLAB and the result is the same, with the difference that now the disp inside the button callback function shows the entire handle structure instead of just the id:
UIControl (ampmin) with properties:
Style: 'edit'
String: '1'
BackgroundColor: [1 1 1]
Callback: #(hObject,eventdata)GUI('ampmin_Callback',hObject,eventdata,guidata(hObject))
Value: 0
Position: [15.6000 14.6154 10.2000 1.6923]
Units: 'characters'
Use get to show all properties
I've also noticed the following:
- If I start the .fig file everything works fine
- If I push the run button on the .m file, the strange behavior described above occurs
Here is the code:
function varargout = GUI2(varargin)
% GUI2 MATLAB code for GUI2.fig
% GUI2, by itself, creates a new GUI2 or raises the existing
% singleton*.
%
% H = GUI2 returns the handle to a new GUI2 or the handle to
% the existing singleton*.
%
% GUI2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in GUI2.M with the given input arguments.
%
% GUI2('Property','Value',...) creates a new GUI2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI2 before GUI2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to GUI2_OpeningFcn via varargin.
%
% *See GUI2 Options on GUIDE Tools menu. Choose "GUI2 allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help GUI2
% Last Modified by GUIDE v2.5 14-Aug-2015 10:39:46
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #GUI2_OpeningFcn, ...
'gui_OutputFcn', #GUI2_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before GUI2 is made visible.
function GUI2_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 GUI2 (see VARARGIN)
% Choose default command line output for GUI2
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes GUI2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = GUI2_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in startAnalysis.
function startAnalysis_Callback(hObject, eventdata, handles)
% hObject handle to startAnalysis (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
disp(handles.ampmin)
function ampmin_Callback(hObject, eventdata, handles)
% hObject handle to ampmin (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 ampmin as text
% str2double(get(hObject,'String')) returns contents of ampmin as a double
handles.ampmin = str2double(get(hObject,'String'));
% Update handles structure
guidata(hObject, handles);
% --- Executes during object creation, after setting all properties.
function ampmin_CreateFcn(hObject, eventdata, handles)
% hObject handle to ampmin (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
handles.ampmin = 1.0;
disp(handles.ampmin)
set(hObject, 'String', num2str(handles.ampmin))
% Update handles structure
guidata(hObject, handles);
Thanks #Hoki, that was the problem. Since I didn't see any direct reference to handles.ampmin I didn't think it would be used to store the handle, but looking at the actual .fig exported code, it became apparent that indeed that's were the uicontrol handle is stored.

How to get varargout to output text from pushbuttons in Matlab GUI?

I am trying to create a GUI using GUIDE where it allows the user to pick one of two pushbuttons. The strings in the pushbuttons will vary each time (I haven't automated this yet), but when any of the pushbuttons is pushed, I'd like the GUI to put out the string as an output variable.
I have the code to where it shows the output in the workspace, but the handles are deleted before the OutputFn is called. Any suggestions on how to fix this?
Also, I'd like to use a 'Next' button. Ideally this should pull up the next two texts to be displayed on the pushbuttons, in an iterative manner, but I'd be happy to move past the hurdle of getting the output for now.Here is what I have so far:
function varargout = Select_A_B(varargin)
% SELECT_A_B MATLAB code for Select_A_B.fig
% SELECT_A_B, by itself, creates a new SELECT_A_B or raises the existing
% singleton*.
%
% H = SELECT_A_B returns the handle to a new SELECT_A_B or the handle to
% the existing singleton*.
%
% SELECT_A_B('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in SELECT_A_B.M with the given input arguments.
%
% SELECT_A_B('Property','Value',...) creates a new SELECT_A_B or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before Select_A_B_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to Select_A_B_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help Select_A_B
% Last Modified by GUIDE v2.5 18-Jun-2015 15:12:42
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #Select_A_B_OpeningFcn, ...
'gui_OutputFcn', #Select_A_B_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before Select_A_B is made visible.
function Select_A_B_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 Select_A_B (see VARARGIN)
% Choose default command line output for Select_A_B
handles.output = hObject;
handles.string = '';
if isempty(varargin)
varargin{1} = 1;
varargin{2} = 1;
end
text1 = varargin{1};
text2 = varargin{2};
A = {'Apple';'Orange'};
B = {'Football';'Basketball'};
set(handles.pushbutton1,'string',A(text1)); % wait until we're ready
set(handles.pushbutton2,'string',B(text2)); % wait until we're ready
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes Select_A_B wait for user response (see UIRESUME)
uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = Select_A_B_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = hObject;
varargout{2} = handles.string;
% --- 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)
selectedButton = get(hObject,'String')
set(handles.string,'String',selectedButton);
guidata(hObject, handles);
close(gcf);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
selectedButton = get(hObject,'String')
set(handles.string,'String',selectedButton);
guidata(hObject, handles);
close(gcf);
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
% --- Executes during object creation, after setting all properties.
function edit1_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: edit controls usually have a white background on Windows.
% See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
set(hObject,'BackgroundColor','white');
end
% --- Executes on button press in pushbutton3.
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)
% --- Executes during object creation, after setting all properties.
function pushbutton1_CreateFcn(hObject, eventdata, handles)
% hObject handle to pushbutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
I have the answer to my question. A summary of changes:
Added uiresume (after adding uiwait in the Opening function) after each Callback
Deleted close (gcf) after each Callback; if the figure closes, then hObject and handles in guidata are no longer accessible to the Output function
Created a handle structure to contain the text of interest and saved that in
guidata after each Callback function
Saved the output from guidata to a .mat file in the Output function
% --- 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)
selectedButton = get(hObject,'String')
handles.string = selectedButton;
guidata(hObject, handles);
uiresume(handles.figure1);
% close(gcf);
function varargout = Select_A_B_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = hObject;
varargout{2} = handles.string;
save 'guioutput'
delete(hObject)
Learnings from the post experience:
I should’ve been more specific regarding my question. Hopefully I’ll
get better with more experience and learning the correct ‘lingo’ to
use.
I should’ve pointed out in my first post that I did spend
considerable time looking at multiple blogs and sites on Matlab GUI,
guide, and guidata. Frankly, none of the sites that I found addressed
my specific question.
This post is the one that finally helped me figure out my mistake:
http://www.mathworks.com/matlabcentral/answers/141809-issue-with-gui-editbox-callback

How to create a GUI to play, pause, fast forward and rewind video in MATLAB?

I am a newbie to MATLAB. I am trying to create a GUI to play, pause, fast forward and rewind an avi video frame by frame. At the moment I can play and pause the video, via a toggle button, but when I press play again the video plays from frame zero. I realise I need to store the frame number to be used the next time I press play but I don't know how to do this.
Any help would be much appreciated. I realise there is an implay option in MATLAB but I have some other code to implement which I have already got right and that is why I want to create my own GUI. Below is the code to pause/play the video.
My most recent code looks like,
function varargout = N_Play_Pause_2(varargin)
% N_PLAY_PAUSE_2 MATLAB code for N_Play_Pause_2.fig
% N_PLAY_PAUSE_2, by itself, creates a new N_PLAY_PAUSE_2 or raises the existing
% singleton*.
%
% H = N_PLAY_PAUSE_2 returns the handle to a new N_PLAY_PAUSE_2 or the handle to
% the existing singleton*.
%
% N_PLAY_PAUSE_2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in N_PLAY_PAUSE_2.M with the given input arguments.
%
% N_PLAY_PAUSE_2('Property','Value',...) creates a new N_PLAY_PAUSE_2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before N_Play_Pause_2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to N_Play_Pause_2_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help N_Play_Pause_2
% Last Modified by GUIDE v2.5 29-Aug-2013 08:39:38
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #N_Play_Pause_2_OpeningFcn, ...
'gui_OutputFcn', #N_Play_Pause_2_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before N_Play_Pause_2 is made visible.
function N_Play_Pause_2_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 N_Play_Pause_2 (see VARARGIN)
% Choose default command line output for N_Play_Pause_2
handles.output = hObject;
handles.VidObj = VideoReader('x05.avi');
handles.nFrames = handles.VidObj.NumberOfFrames;
handles.videoPos = 1; %Current video position. Starts at 1.
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes N_Play_Pause_2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = N_Play_Pause_2_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
while get(hObject,'Value')
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
if handles.videoPos >= handles.nFrames % Protect your code not to go be number of frames available
break;
end
handles.videoPos=handles.videoPos+1; % Increment the stored position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
set(hObject,'Value',false);
% --- 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)
if get(hObject,'Value')
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
handles.videoPos=handles.videoPos+1; % Increment the stored position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
set(hObject,'Value',false);
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value')
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
handles.videoPos=handles.videoPos-1; % Increment the stored position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
set(hObject,'Value',false);
% --- Executes on button press in pushbutton3.
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)
if get(hObject,'Value')
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
handles.videoPos=handles.videoPos+10; % Increment the stored position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
set(hObject,'Value',false);
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value')
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
handles.videoPos=handles.videoPos-10; % Increment the stored position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
set(hObject,'Value',false);
Final solution
So, I haven't seen that you updated your code. Seeing your code is quite easier, it seems that you are incrementing after you show your image, so if you push the play button it will show the image before
function varargout = N_Play_Pause2(varargin)
% N_PLAY_PAUSE2 MATLAB code for N_Play_Pause2.fig
% N_PLAY_PAUSE2, by itself, creates a new N_PLAY_PAUSE2 or raises the existing
% singleton*.
%
% H = N_PLAY_PAUSE2 returns the handle to a new N_PLAY_PAUSE2 or the handle to
% the existing singleton*.
%
% N_PLAY_PAUSE2('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in N_PLAY_PAUSE2.M with the given input arguments.
%
% N_PLAY_PAUSE2('Property','Value',...) creates a new N_PLAY_PAUSE2 or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before N_Play_Pause2_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to N_Play_Pause2_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help N_Play_Pause2
% Last Modified by GUIDE v2.5 23-Aug-2013 13:50:30
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #N_Play_Pause2_OpeningFcn, ...
'gui_OutputFcn', #N_Play_Pause2_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before N_Play_Pause2 is made visible.
function N_Play_Pause2_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 N_Play_Pause2 (see VARARGIN)
handles.output = hObject;
handles.VidObj = VideoReader('x05.avi');
handles.nFrames = handles.VidObj.NumberOfFrames;
handles.videoPos = 1; % Current video position, starts at first frame.
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(handles.videoPos);
% Choose default command line output for N_Play_Pause2
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes N_Play_Pause2 wait for user response (see UIRESUME)
% uiwait(handles.figure1);
% --- Outputs from this function are returned to the command line.
function varargout = N_Play_Pause2_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
while get(hObject,'Value') && handles.videoPos < handles.nFrames
handles.videoPos=handles.videoPos+1; % Increment the stored position
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(handles.videoPos);
end
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
% --- 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)
if get(hObject,'Value')
handles.videoPos=handles.videoPos+1; % Increment the stored position
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value') && handles.videoPos>1
handles.videoPos=handles.videoPos-1; % Increment the stored position
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
% --- Executes on button press in pushbutton3.
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)
if get(hObject,'Value') && handles.videoPos<handles.nFrames-9
handles.videoPos=handles.videoPos+10; % Increment the stored position
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
% --- Executes on button press in pushbutton4.
function pushbutton4_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton4 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if get(hObject,'Value') && handles.videoPos>10
handles.videoPos=handles.videoPos-10; % Increment the stored position
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(handles.videoPos);
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
Seems you got confused a little bit with the coding, I've edited it and commented your errors.
They are preceded by % COMMENT:
function varargout = N_Play_Pause(varargin)
% N_PLAY_PAUSE MATLAB code for N_Play_Pause.fig
% N_PLAY_PAUSE, by itself, creates a new N_PLAY_PAUSE or raises the existing
% singleton*.
%
% H = N_PLAY_PAUSE returns the handle to a new N_PLAY_PAUSE or the handle to
% the existing singleton*.
%
% N_PLAY_PAUSE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in N_PLAY_PAUSE.M with the given input arguments.
%
% N_PLAY_PAUSE('Property','Value',...) creates a new N_PLAY_PAUSE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before N_Play_Pause_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to N_Play_Pause_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES
% Edit the above text to modify the response to help N_Play_Pause
% Last Modified by GUIDE v2.5 13-Aug-2013 16:26:32
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', #N_Play_Pause_OpeningFcn, ...
'gui_OutputFcn', #N_Play_Pause_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% --- Executes just before N_Play_Pause is made visible.
function N_Play_Pause_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 N_Play_Pause (see VARARGIN)
% Choose default command line output for N_Play_Pause
handles.output = hObject;
handles.VidObj = VideoReader('x05.avi'); % COMMENT: PAY ATTENTION, 's' was missing!
handles.nFrames = handle.VidObj.NumberOfFrames;
handles.videoPos = 1; % Current video position, starts at first frame.
% Update handles structure
guidata(hObject, handles); % Here you are saving the handles method at the hObject, this is the handle from your GUI figure.
% COMMENT: In the original code here, you would save guidata twice, you didn't need that, just save guidata after you make ALL ALTERATIONS IN IT!
% --- Outputs from this function are returned to the command line.
function varargout = N_Play_Pause_OutputFcn(hObject, eventdata, handles)
% varargout cell array for returning output args (see VARARGOUT);
% hObject handle to figure
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Get default command line output from handles structure
varargout{1} = handles.output;
% --- Executes on button press in togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
while get(hObject,'Value')
snapshot = read(handles.VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(double2str(handles.videoPos));
if handles.videoPos >= handles.nFrames % Protect your code not to go be number of frames available
break;
end
handles.videoPos=handles.videoPos+1; % Increment the stored position
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
Reading your question title I was like, what else you need? Do you also want a desert? But jokes a part, I was wrong, at least you have something working.
I am not an image specialist at matlab, but instead doing a = 0 in your callback function (and therefore reseting your video to start position), you will need to save your video position at your GUI. There are several ways of doing it, one way would be by using guidata, setappdata, or to pass it via arguments to your callbacks. You could call it a variable videoPos and add it to the handles struct that you store with guidata. Also save your nFrames variable in this struct.
The fast forward would be the same as you showed, but instead doing videoPos = videoPos + 1 you would do videoPos = videoPos + n, where n is the speed multiplier you want on the fast forward. To rewind, just decrement your videoPos, or reset it to 1, depending what you want.
Note: Don't forget to add checkers, you won't want your videoPos lesser than 0 or greater than nFrames.
On the function: N_Play_Pause_OpeningFcn Add the following data:
handle.VidObj = VideoReader('x05.avi');
handle.nFrames = VidObj.NumberOfFrames;
handle.videoPos = 1; % Current video position, starts at first frame.
% Update handles structure
guidata(hObject, handles); % Here you are saving the handles method at the hObject, this is the handle from your GUI figure.
Then, at your function togglebutton1_Callback do:
% --- Executes on button press in togglebutton1.
function togglebutton1_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton1
% You won't need this line anymore a=0;
% If you would like to retrieve the stored guidata you would do it here, by doing **handles=guidata(hObject);** but this is not needed, the handles data stored at the figure handle is already given to you as the third argument internally by the matlab!
while get(hObject,'Value')
snapshot = read(VidObj,handles.videoPos); % Here we use the stored video position
imshow(snapshot),title(double2str(handles.videoPos));
if handles.videoPos >= handles.nFrames % Protect your code not to go be number of frames available
break;
end
handles.videoPos=handles.videoPos+1; % Increment the stored position
end
guidata(hObject,handles) % Save the modifications done at the handles structure at the figure handle
Note that you need to update the guidata everytime you quit your methods, so that you keep it updated and saved on the figure handle. One more detail is that the object you pass for the guidata don't need to be the figure handle, but any object holden by it, as the play button you have created. As in the guidata help:
GUIDATA(H, DATA) stores the specified data in the figure's
application data.
H is a handle that identifies the figure - it can be the figure
itself, or any object contained in the figure.
Now just add more buttons and work with the togglebutton1 method, the fastforward would be the same, but using instead of +1, +n.