Reputation: 29
I created a listbox
and enabled multiple selections. My listbox
contain numbers from 1 to 10. When I select 3, 1, and 8, the function always put my selections in alphabetical order (1,3,8). Is there any way I could make it not put my selection in alphabetical order? So if I select 3, 1, and 8 the output of my selection is 3, 1, 8.
Thank you.
Upvotes: 0
Views: 2448
Reputation: 24179
For the purpose of this answer I'm assuming you're using matlab-hg2.
From the docs for uicontrol
:
'listbox'
... TheValue
property stores the row indexes of currently selected list box items, and is a vector value when you select multiple items. After any mouse button up event that changes theValue
property, MATLAB evaluates the list box's callback routine. To delay action when multiple items can be selected, you can associate a "Done" push button with the list box. Use the callback for that button to evaluate the list boxValue
property.
From the above we learn that the information on the selected lines is returned in Value
. From there, it's a matter of keeping track of what's selected. This can be quite easily done using a persistent
variable inside the listbox' Callback
as shown in the following example:
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
Example output:
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
Then it's up to you to assign the value of previouslyChosenItems
somplace useful.
Upvotes: 3