8

Say I have two arrays where one is a permutation of the other:

A = [2 1 5 3 7]
B = [7 2 1 3 5]

with no repetitions in either array.

How can I obtain the permutation mapping between both?

E.g. A->B should be:

[2, 3, 5, 4, 1]

which means:

A(1) -> B(2)
A(2) -> B(3)
A(3) -> B(5)
A(4) -> B(4)
A(5) -> B(1)

Update:

Is there a fast vectorized solution that does not use ismember ? In my experience, ismember tends to be slow for very large arrays.

1
  • Is it guaranteed that the elements of A and B are unique? Commented Mar 28, 2012 at 1:24

4 Answers 4

19

How about this:

[i a] = sort(A);
[i b] = sort(B);
mapping = b(a)
Sign up to request clarification or add additional context in comments.

4 Comments

Speed is about 2x better than ismember.
Somebody else already did all the hard work optimizing sort. :)
Apparently it is just a quick sort (so we know who "somebody" is). BTW the performance ratio is about the same across >5 orders of magnitude of array sizes.
You may get speedup if you sort both vectors in the same call. I believe some versions of Matlab do a better job multithreading in this case? Depending on your hardware, you might also get significantly better speed by sorting in-place, which would require a Mex function.
7

Use ismember.

[~,idx] = ismember(A,B);

The vector idx will contain indices such that B(idx) == A.

Note that ismember finds the highest indices.

Comments

1

You can also use knnsearch, but for not repeated members in both a and b

Comments

0

Try this:

for i=1:size(B)
C(:,i) = [i find(B==A(i))]
end

2 Comments

This will cause problems if more than one element of B is equal to an element of A.
and is less efficient than other solutions

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.