Return popupmenu selection in MATLAB using one line of code

Doresoom picture Doresoom · May 3, 2010 · Viewed 31.6k times · Source

I have a GUI which uses a selection from a popupmenu in another callback. Is there a way to return the selected value of the popupmenu in only one line without creating any temporary variables? I've tried several solutions, but I've only managed two lines with one temporary variable:

Three lines:

list=get(handles.popupmenu1,'String');
val=get(handles.popupmenu1,'Value');
str=list{val};

Two lines:

temp=get(handles.popupmenu1,{'String','Value'});
str=temp{1}{temp{2}};

Can anyone shave it down to one?

PS, It's a dynamic menu, so I can't just use get(handles.popupmenu1,'Value') and ignore the string component altogether.

Answer

Jonas picture Jonas · May 3, 2010

Here's a one-liner:

str = getCurrentPopupString(handles.popupmenu1);

And here's the definition of getCurrentPopupString

function str = getCurrentPopupString(hh)
%# getCurrentPopupString returns the currently selected string in the popupmenu with handle hh

%# could test input here
if ~ishandle(hh) || strcmp(get(hh,'Type'),'popupmenu')
error('getCurrentPopupString needs a handle to a popupmenu as input')
end

%# get the string - do it the readable way
list = get(hh,'String');
val = get(hh,'Value');
if iscell(list)
   str = list{val};
else
   str = list(val,:);
end

I know that's not the answer you were looking for, but it does answer the question you asked :)