我有两个具有相同元素的向量,但它们的顺序不同。例如
一个
10
9
8B
8
9
10我想找出两者之间的映射
B2A
3
2
1我怎样才能在matlab中高效地做这件事?
发布于 2014-02-15 06:31:32
我认为Matlab排序是有效的。所以:
[~,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“中,那么下面的代码应该是对它的检查
N=1e4;
M=100;
A=floor(M*rand(1,N));
[~,I]=sort(rand(1,N));
B=A(I);
findB2A;
all(A==B(B2A))发布于 2014-02-15 04:15:12
这里有一个解决方案:
arrayfun(@(x)find(x == B), A)我尝试使用更大的数组:
A = [ 7 5 2 9 1];
B = [ 1 9 7 5 2];它提供了以下结果:
ans =
3 4 5 2 1编辑
因为arrayfun通常比等效的循环慢,所以这里是一个带循环的解决方案:
T = length(A);
B2A = zeros(1, length(A));
for tt = 1:T
B2A(1, tt) = find(A(tt) == B);
end发布于 2014-02-15 04:15:28
有几种方法可以做到这一点。就代码行而言,最有效的可能是使用ismember()。返回值为[Lia,Locb] = ismember(A,B),其中Locb是B中与A元素相对应的索引。您可以执行[~, B2A] = ismember(A, B)来获得您想要的结果。如果您的MATLAB版本不允许使用~,请为第一个输出提供一个一次性参数。
您必须确保存在一对一的映射才能获得有意义的结果,否则索引将始终指向第一个匹配的元素。
https://stackoverflow.com/questions/21788606
复制相似问题