MATLAB: How to get value of uicontrol object whose callback is executing

callbackMATLABmatlab gui

I have a GUI with a variable number of uicontrol pushbuttons which share a single callback function. In order to make this work, I am using the value of each of the buttons to determine how to handle the data being given. I assumed I would be able to use get(gcbo,'Value') in the callback function to determine which button was pressed, but for every button it simply returns 1. I have checked that each uicontrol object has a unique value. Here is a simplified example of my code:
handles.browse(i) = uicontrol('Style','pushbutton',...
'String','...',...
'Value',i,...
'TooltipString','Browse for a file.',...
'Position',[5 ypos-20 20 27],...
'Callback', @Browse);
function Browse(varargin)
val = get(gcbo,'Value');
[filename,path,index] = uigetfile('*.mat','Locate File');
if index
output{val} = [path filename];
end
end
Please keep in mind that I am working with version R2010b, though this shouldn't be an issue.

Best Answer

The property 'Value' of a button is either 0 or 1 and you cannot use it to store data. But you can use the UserData, add an input to the callback or compare the handle of the pressed button with the list of button handles:
function main
FigH = figure;
for index = 1:5
handles.browse(index) = uicontrol('Style','pushbutton',...
'String', sprintf('%d', index), ...
'Position',[5 k*22 20 20],...
'Callback', {@Browse, index}, ... % Provide index as 3rd input
'UserData', index); % Alternative 1: UserData
end
% Alternatively 2: store the button handles:
guidata(FigH, handles);
end
function Browse(ButtonH, EventData, index)
disp(index);
% Alternative 1:
index1 = get(ButtonH, 'UserData');
disp(index1)
% Alternative 2:
handles = guidata(ButtonH);
index2 = find(handles.browse == ButtonH);
disp(index2)
end
All three methods let the callback identify, which button was pressed.
By the way, using the handle provided as 1st input of the callback is more direct than requesting gcbo.