使用一行代码在MATLAB中返回弹出菜单选择

Dor*_*oom 5 matlab user-interface popupmenu

我有一个GUI,它使用另一个回调中弹出菜单的选择.有没有办法只在一行中返回弹出菜单的选定值而不创建任何临时变量?我已经尝试了几种解决方案,但我只使用一个临时变量管理了两行:

三行:

list=get(handles.popupmenu1,'String');
val=get(handles.popupmenu1,'Value');
str=list{val};
Run Code Online (Sandbox Code Playgroud)

两行:

temp=get(handles.popupmenu1,{'String','Value'});
str=temp{1}{temp{2}};
Run Code Online (Sandbox Code Playgroud)

任何人都可以把它剃成一个吗?

PS,这是一个动态菜单,所以我不能只使用get(handles.popupmenu1,'Value')和忽略字符串组件.

Jon*_*nas 11

这是一个单行:

str = getCurrentPopupString(handles.popupmenu1);
Run Code Online (Sandbox Code Playgroud)

这是定义 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
Run Code Online (Sandbox Code Playgroud)

我知道这不是你要找的答案,但它确实回答了你问的问题:)

  • @Jonas:Touché,为我的OCD问题提供实用的解决方案. (3认同)

gno*_*ice 5

为了使它成为一个单行,我只是创建我自己的功能(即getMenuSelection),就像Jonas在他的回答中所说明的那样.如果你真的想要一个真正的单行,这里有一个使用CELLFUN:

str = cellfun(@(a,b) a{b},{get(handles.popupmenu1,'String')},{get(handles.popupmenu1,'Value')});
Run Code Online (Sandbox Code Playgroud)

非常丑陋,难以阅读.我一定会去写自己的功能.

编辑:这是一个使用FEVAL的略短(但仍然同样丑陋)的单线程:

str = feval(@(x) x{1}{x{2}},get(handles.popupmenu1,{'String','Value'}));
Run Code Online (Sandbox Code Playgroud)


Yai*_*man 5

我知道这是愚蠢的,但我无法抗拒:

list=get(handles.popupmenu1,'String'); str=list{get(handles.popupmenu1,'Value')};
Run Code Online (Sandbox Code Playgroud)

我知道这不是你的意思,但就像上面的其他答案一样,它确实回答了你的问题...... :-)