列表框多选matlab

时间:2015-11-29 15:40:37

标签: matlab matlab-figure matlab-gui

我创建了listbox并启用了多项选择。我的listbox包含从1到10的数字。当我选择3,1和8时,该函数总是按字母顺序(1,3,8)进行选择。有什么方法可以让我不按字母顺序排列我的选择吗?因此,如果我选择3,1和8,我选择的输出是3,1,8。

谢谢。

1 个答案:

答案 0 :(得分:3)

出于这个答案的目的,我假设你正在使用

来自uicontrol的文档:

  
      
  • 'listbox' ... Value属性存储当前所选列表框项的行索引,并且是选择多个项时的矢量值。在任何更改Value属性的鼠标按钮事件之后,MATLAB会评估列表框的回调例程。要在可以选择多个项目时延迟操作,您可以将“完成”按钮与列表框关联。使用该按钮的回调来评估列表框Value属性。
  •   

从上面我们了解到所选行的信息在Value中返回。从那里,这是一个跟踪所选内容的问题。使用列表框“persistent中的Callback变量可以非常轻松地完成此操作,如以下示例所示:

function LISTBOX_EXAMPLE
hFig = figure('Units','Pixels','Position', [200 200 100 200],'Menubar','none');
uicontrol(hFig, ...
  'Style', 'listbox',...
  'Units','Pixels',...
  'Position', [20 20 80 150],...
  'Max',3,...
  'Min',0,...
  'String',num2cell(1:10),...
  'Callback',@selectionCallback);

  function selectionCallback(hObject,~)
    persistent previouslyChosenItems
    %// Elements were added:    
    if numel(previouslyChosenItems) < numel(hObject.Value)
      previouslyChosenItems = union(previouslyChosenItems,hObject.Value,'stable');
    %// Elements were removed:
    elseif numel(previouslyChosenItems) > numel(hObject.Value)
      previouslyChosenItems = intersect(previouslyChosenItems,hObject.Value,'stable');
    %// A different element was selected (single element):
    elseif numel(previouslyChosenItems) == numel(hObject.Value) && numel(hObject.Value)==1
      previouslyChosenItems = hObject.Value;
    end
    disp(['Currently selected items (in order): ' num2str(previouslyChosenItems(:)')]);
  end

end

示例输出:

Currently selected items (in order): 7
Currently selected items (in order): 3
Currently selected items (in order): 3  9
Currently selected items (in order): 3  9  1

然后由你来分配previouslyChosenItems somplace有用的值。