开发者

Return popupmenu selection in MATLAB using one line of code

开发者 https://www.devze.com 2022-12-28 19:35 出处:网络
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

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.popupm开发者_开发技巧enu1,'Value') and ignore the string component altogether.


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


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'}));
0

精彩评论

暂无评论...
验证码 换一张
取 消