Question

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.

Was it helpful?

Solution

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 :)

OTHER TIPS

I know this is stupid, but I couldn't resist:

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

I know that's not what you meant, but like the other answers above, it does answer your question... :-)

To make it a one-liner, I would simply create my own function (i.e. getMenuSelection) like Jonas illustrates in his answer. If you really want a true one-liner, here's one using CELLFUN:

str = cellfun(@(a,b) a{b},{get(handles.popupmenu1,'String')},{get(handles.popupmenu1,'Value')});

Very ugly and hard to read. I'd definitely go with writing my own function.

EDIT: And here's a slightly shorter (yet still equally ugly) one-liner using FEVAL:

str = feval(@(x) x{1}{x{2}},get(handles.popupmenu1,{'String','Value'}));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top