Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96284

Getting the mapping for a permutation in MATLAB

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.

Upvotes: 8

Views: 2460

Answers (4)

remo
remo

Reputation: 898

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

Upvotes: 1

Nate
Nate

Reputation: 3038

How about this:

[i a] = sort(A);
[i b] = sort(B);
mapping = b(a)

Upvotes: 19

reve_etrange
reve_etrange

Reputation: 2571

Use ismember.

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

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

Note that ismember finds the highest indices.

Upvotes: 7

nitin
nitin

Reputation: 7358

Try this:

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

Upvotes: 0

Related Questions