Zanam
Zanam

Reputation: 4807

Using find function

Consider the following arrays:

A = [1 3 4 5 6 7 1 3 7];
B = [1 4 7];

I want to find all elements of B in array A. So, my final output array will look something like:

C = [1 7 3 6 9];

First element of B is at locations 1 and 7 in array A, so C has 1 and 7 as first two elements. Element 4 of B is at location 3, so array C has 3 as its third element and so on.

Upvotes: 0

Views: 64

Answers (3)

chappjc
chappjc

Reputation: 30589

Second output of ismember will give a map for each element of B

>> [~,ic] = ismember(A,B)
ic =
     1     0     2     0     0     3     1     0     3

Then element-wise test against each element of B:

>> [C,~] = find(bsxfun(@eq,ic.',1:numel(B)))
C =
     1
     7
     3
     6
     9

And because I'm require to do so, an alternative method following ismember:

c = accumarray(nonzeros(ic),find(ic),[],@(x) {sort(x)});
C = vertcat(c{:})

Upvotes: 1

Luis Mendo
Luis Mendo

Reputation: 112769

If you need the result in that order: you can use the two outputs of ismember. This may be faster than Daniel's answer (second part) as it avoids arrayfun:

[tf, loc] = ismember(A,B);
loc = loc(tf);
ind = find(tf);
[~, order] = sort(loc);
C = ind(order);

Upvotes: 2

Daniel
Daniel

Reputation: 36720

The order of C is required?

Fast, but another order:

find(ismember(A,B))

Slower, but the order you want:

cell2mat(arrayfun(@(x)(find(A==x)),B,'UniformOutput',false))

Basically, the second solution iterates over all elements of B and applies find(A==x) in a loop.

You may also delete the cell2mat, then a cell is returned. First element -> Occurrences of 1, second element-> occurrences of 4 etc.

Upvotes: 4

Related Questions