6

別のコールバックで popupmenu からの選択を使用する GUI があります。一時変数を作成せずに、popupmenu の選択した値を 1 行だけで返す方法はありますか? いくつかの解決策を試しましたが、1 つの一時変数で 2 行しか管理できませんでした。

3 行:

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

2 行:

temp=get(handles.popupmenu1,{'String','Value'});
str=temp{1}{temp{2}};

誰でも1つに削ることができますか?

PS、これは動的メニューなのでget(handles.popupmenu1,'Value')、文字列コンポーネントをそのまま使用して無視することはできません。

4

3 に答える 3

11

これがワンライナーです:

str = getCurrentPopupString(handles.popupmenu1);

そしてここにの定義があります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

私はそれがあなたが探していた答えではないことを知っています、しかしそれはあなたが尋ねた質問に答えます:)

于 2010-05-03T18:01:56.567 に答える
5

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

于 2010-05-03T20:40:39.223 に答える
5

ワンライナーにするために、ジョナスが彼の答えで示しているように、私は単に独自の関数(つまりgetMenuSelection)を作成します。真のワンライナーが本当に必要な場合は、 CELLFUNを使用したものを次に示します。

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

非常に醜く、読みにくい。私は間違いなく自分の関数を書くことに行きます。

編集:そして、これはFEVALを使用した少し短い (それでも同じように醜い) ワンライナーです:

str = feval(@(x) x{1}{x{2}},get(handles.popupmenu1,{'String','Value'}));
于 2010-05-03T18:08:25.433 に答える