0

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);

1 Comment

More memory efficient than mine.
1

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{:})

2 Comments

+1 for bsxfun. But it may consume much memory for large A and B.
True, bsxfun can be quite memory heavy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.