MATLAB: How to select only two items from a list box in MATLAB 7.6 (R2008a)

MATLAB

I want to select only two items from a list box, it should not take more than two selection of items in the list box. Is there a way to do this in MATLAB?

Best Answer

You can modify the listbox's callback function to acheive this functionality.
The code for the callback is shown below:
function listbox1_Callback(hObject, eventdata, handles)
% hObject handle to listbox1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox1 contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox1
persistent option1 option2
selections = get(hObject,'Value');
if size(selections,2) == 2
option1 = selections(1);
option2 = selections(2);
% Apply some application logic here

contents = cellstr(get(hObject,'String'));
disp([contents{option1},' was selected']);
disp([contents{option2},' was selected']);
elseif size(selections,2) == 3
% Ignore everything but the last two choices
newChoice = setdiff(selections,[option1, option2]);
option1 = option2;
option2 = newChoice;
% Apply some application logic here
contents = cellstr(get(hObject,'String'));
disp([contents{option1},' was selected']);
disp([contents{option2},' was selected']);
% Update the Listbox UICONTROL to make it seem like only the last two
% were selected
set(hObject,'Value',[option1, option2]);
end
Links to the relevant files are provided below.