Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return popupmenu selection in MATLAB using one line of code

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.

like image 964
Doresoom Avatar asked May 03 '10 17:05

Doresoom


3 Answers

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

like image 173
Jonas Avatar answered Nov 12 '22 08:11

Jonas


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

like image 22
Yair Altman Avatar answered Nov 12 '22 09:11

Yair Altman


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'}));
like image 34
gnovice Avatar answered Nov 12 '22 07:11

gnovice