0
votes

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.

3

3 Answers

2
votes

You could use ismember

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

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
2
votes

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