How to find index of value based on value from a different variable?

  • I have variable X that contains ~50 names.
  • I have variable Y that contains a directory of 200 files, of which 50 match the name of variable X.
I would like to look into the Y variable, and for each name that matches a name within variable X, I would like to return that matche's index within Y variable.
  • In other words, I would like to know the location of each duplicate's name in variable Y, for future use.
I tried extracting the names from variable Y into a new variable, so that I can then use a find function. But I am having trouble.
% create Y2 that stores only the names from directory Y
for tmp = 1:length(Y)
Y2(tmp)= string(Y(tmp).name);
end
% however, this returns only NaN values and I'm not sure why
%% use ? function to compare list of names in X to Y2
%% For each match in name, get Y2's index position.

 Accepted Answer

Try ismember():
[~, index] = ismember(Y, X); % Find what index Y is in the list of the 50 names that comprise X.

More Answers (0)

Asked:

on 17 Dec 2019

Answered:

on 17 Dec 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!