user4704857
user4704857

Reputation: 469

Matching cell arrays in MATLAB

I am trying to find indices of the elements in one cell array in another cell array in MATLAB. For example:

a = {'Hello', 'Good', 'Sun', 'Moon'};
b = {'Well', 'I', 'You', 'Hello', 'Alone', 'Party', 'Long', 'Moon'};

I expect to get the following result which shows the index of elements of $a$ in array $b$:

index=[4, NaN, NaN, 8];

I know it is possible to implement it using loops, but I think there is simple way to do that which I don't know.

Thanks.

Upvotes: 0

Views: 372

Answers (3)

Rascarcapac
Rascarcapac

Reputation: 123

you can use the 2nd output argument of ismember:

[ida,idb]=ismember(a, b)

ida =    1     0     0     1
idb=     4     0     0     8

If you really need NaN just do:

idb( idb == 0 ) = NaN

Upvotes: 2

matlabgui
matlabgui

Reputation: 5672

You could use ismember

[flag,index] = ismember ( a, b )

Upvotes: 2

Divakar
Divakar

Reputation: 221744

With ismember -

[matches,index] = ismember(a,b)
index(~matches) = nan

With intersect -

[~,pos,idx] = intersect(a,b)
index = nan(1,numel(a))
index(pos) = idx

Upvotes: 3

Related Questions