两个向量的映射ID [英] Mapping ids of two vectors
本文介绍了两个向量的映射ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个具有相同元素的向量,但它们的顺序不相同.对于例如
I have two vectors with the same elements but their order is not same. For eg
A
10
9
8
B
8
9
10
我想找到两者之间的映射
I want to find the mapping between the two
B2A
3
2
1
如何在matlab中有效地做到这一点?
How can I do this in matlab efficiently?
推荐答案
我认为Matlab排序是有效的.所以:
I think the Matlab sort is efficient. So:
[~,I]=sort(A); %sort A; we want the indices, not the values
[~,J]=sort(B); %same with B
%I(1) and J(1) both point to the smallest value, and a similar statement is true
%for other pairs, even with repeated values.
%Now, find the index vector that sorts I
[~,K]=sort(I);
%if K(1) is k, then A(k) is the kth smallest entry in A, and the kth smallest
%entry in B is J(k)
%so B2A(1)=J(k)=J(K(1)), where BSA is the desired permutation vector
% A similar statement holds for the other entries
%so finally
B2A=J(K);
如果上述内容在脚本"findB2A"中,则应检查以下内容
if the above were in script "findB2A" the following should be a check for it
N=1e4;
M=100;
A=floor(M*rand(1,N));
[~,I]=sort(rand(1,N));
B=A(I);
findB2A;
all(A==B(B2A))
这篇关于两个向量的映射ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文