MATLAB Answers


How to find position of a number in an array using a drop down

Asked by Adrian Quesada on 21 May 2019
Latest activity Edited by Adam Danz
on 22 May 2019
Lets say P=[1 2 3;4 5 6; 7 8 9] is there any way to use a drop down in GUI or App Designer to search for a value in the first column and that the code returns the second and third value of the same row?.
The final array have 100 rows, so if I use cases on the drop down the code will be so big.
Thanks for your help

  1 Comment

Drop down menus merely present a list that allows the user to select one or more items. Drop down menus do not "search" for anything.
It would be easy to create a drop down list of all items in the first row of the matrix. Is it your intention that the user would then select one of those items and then return the other items in that row? If that's the case, are all items in row 1 unique or will there be more than 1 row with the same number in the first column? Are your data all integers?

Sign in to comment.

1 Answer

Answer by Adam Danz
on 21 May 2019
Edited by Adam Danz
on 22 May 2019
 Accepted Answer

Here's how to create a quick UI dropdown list populated with values from column 1 of your matrix. After the user make a selection, values from columns 2 and 3 appear in the text box. To run it, copy and paste into a script and run the script.
% Your matrix data
P = reshape(1:300,3,[])';
% Create UI figure with dropdown
fig = uifigure;
fig.Position([3,4]) = [215,275];
dd = uidropdown(fig);
dd.Position = [60,220,100,22];
% Store first row of matrix in dropdown
dd.Items = strsplit(num2str(P(:,1)'));
% add a text area to display results
txa = uitextarea(fig);
txa.Position = [20,100,180,22];
txa.HorizontalAlignment = 'center';
txa.Editable = 'off';
% Assign callback function (after txa is created)
dd.ValueChangedFcn = @(dd,event)valueSelectionCallback(dd,txa,P);
% Create callback function to respond to user selection
function valueSelectionCallback(dd, txa, P)
% Return columns 2 and 3 from the row selected
v = P(P(:,1) == str2double(dd.Value), [2,3]);
% Update the text box with vector
txa.Editable = 'on';
txa.Value = sprintf('[%s]', num2str(v));
txa.Editable = 'off';


Sign in to comment.