MATLAB: One function for an infinite amount of pushbuttons in matlab

MATLABmatlab functionmatlab gui

So I was trying to create something that is similar to this testGUI below. But instead of actually limiting the numbers of buttons to 3. There would be any amount of pushbuttons linked to one function. But all the pushbuttons do the same thing but slightly different depending on the button pressed.
function testGUI
handles.mainwindow = figure();
handles.mytextbox = uicontrol( ...
'Style', 'edit', ...
'Units', 'normalized', ...
'Position', [0.15 0.80 .70 .10], ...
'String', 'No Button Has Been Pressed' ...
);
handles.button(1) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.05 0.05 .30 .70], ...
'String', 'Button1', ...
'Callback', {@mybuttonpress,handles} ...
);
handles.button(2) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.35 0.05 .30 .70], ...
'String', 'Button2', ...
'Callback', {@mybuttonpress,handles} ...
);
handles.button(3) = uicontrol( ...
'Style', 'pushbutton', ...
'Units', 'normalized', ...
'Position', [0.65 0.05 .30 .70], ...
'String', 'Button3', ...
'Callback', {@mybuttonpress,handles} ...
);
end
function mybuttonpress(src, ~, handles)
switch src.String
case 'Button1'
handles.mytextbox.String = 'Button 1 Has Been Pressed';
case 'Button2'
handles.mytextbox.String = 'Button 2 Has Been Pressed';
case 'Button3'
handles.mytextbox.String = 'Button 3 Has Been Pressed';
otherwise
% Something strange happened
end
end

Best Answer

You can compares src directly to a list of handles to identify the button used and then make your decision based on this:
function lotsofbuttons
n = 10;
pbs = gobjects(n,1); % Store pushbuttons here
for ii = 1:n;
pbs(ii) = uicontrol('Style','Pushbutton','Units','normalized','Position',rand(1,4)./2,'Callback',@TheCallback);
end
function TheCallback(src,~)
idx = find(pbs==src); % Compare list to source
disp(['Pushbutton ' num2str(idx)])
end
end