views:

589

answers:

3

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.

+4  A: 

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');
str = list{val};

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

Jonas
@Jonas: Touché, for giving me a practical solution to my OCD question.
Doresoom
+1: Just what I was thinking.
gnovice
+3  A: 

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'}));
gnovice
+1 for giving me the answer that I actually wanted, however impractical it may be
Doresoom
+1 for answering the question as intended. `cellfun` FTW!
Jonas
+3  A: 

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

Yair Altman
+1 for not resisting :)
Jonas
+1 I had a feeling I'd see this when I asked the question :)
Doresoom