MATLAB: Index of the items in a listbox

app designerlistboxorder

Using app designer, is it possible to get the index of the selected items from the listbox?
Example: I have 6 items in the listbox; data1, data2, vector1, vector2, vector3 and emc.
If data1, vector1, vector2 and emc are selected, I want to read the location of these items in the listbox, which is 1, 3, 4, 6.

Best Answer

I'm not sure what you mean by order. The value property of the listbox tells you which items are selected, so in your example you'll get {'data1', 'vector1', 'vector2', 'emc'}. If you want the index of selected elements, you can either pass your selection to ismember and get its second output, or fill the ItemsData property with the indices:
  • using ismember:
listitems = {'data1', 'data2', 'vector1', 'vector2', 'vector3', 'emc'};
hfig = uifigure;
hbox = uilistbox(hfig, 'Items', listitems, 'Multiselect', 'on');
hbox.Value = {'data1', 'vector1', 'vector2', 'emc'}; %simulate user selection

%get index of selected values

[~, index] = ismember(hbox.Value, hbox.Items)
  • using ItemsData:
listitems = {'data1', 'data2', 'vector1', 'vector2', 'vector3', 'emc'};
hfig = uifigure;
hbox = uilistbox(hfig, 'Items', listitems, 'ItemsData', 1:numel(listitems), 'Multiselect', 'on');
hbox.Value = [1 3 4 6]; %simulate user selection
%get index of selected values
index = hbox.Value %returns corresponding ItemsData