我需要帮助优化此循环。matrix_1
为(n
×2)的INT矩阵和matrix_2
为(m
×2), m
&n
很。
index_j = 1;
for index_k = 1:size(Matrix_1,1)
for index_l = 1:size(Matrix_2,1)
M2_Index_Dist(index_j,:) = [index_l, sqrt(bsxfun(@plus,sum(Matrix_1(index_k,:).^2,2),sum(Matrix_2(index_l,:).^2,2)')-2*(Matrix_1(index_k,:)*Matrix_2(index_l,:)'))];
index_j = index_j + 1;
end
end
我需要M2_Index_Dist
提供一个((n*m)
x 2)矩阵,matrix_2
其中第一列的索引为,第二列的距离为。
输出示例:
M2_Index_Dist = [ 1, 5.465
2, 56.52
3, 6.21
1, 35.3
2, 56.52
3, 0
1, 43.5
2, 9.3
3, 236.1
1, 8.2
2, 56.52
3, 5.582]
以下是适用bsxfun
于您的公式(||A-B|| = sqrt(||A||^2 + ||B||^2 - 2*A*B)
)的方法:
d = real(sqrt(bsxfun(@plus, dot(Matrix_1,Matrix_1,2), ...
bsxfun(@minus, dot(Matrix_2,Matrix_2,2).', 2 * Matrix_1*Matrix_2.')))).';
如果更改矩阵的解释,则可以避免最终的转置。
注意:不应有任何复杂的值要处理,real
但在很小的差异可能会导致极小的负数的情况下存在。
编辑:可能会更快dot
:
d = sqrt(bsxfun(@plus, sum(Matrix_1.*Matrix_1,2), ...
bsxfun(@minus, sum(Matrix_2.*Matrix_2,2)', 2 * Matrix_1*Matrix_2.'))).';
或只需打一个电话bsxfun
:
d = sqrt(bsxfun(@plus, sum(Matrix_1.*Matrix_1,2), sum(Matrix_2.*Matrix_2,2)') ...
- 2 * Matrix_1*Matrix_2.').';
注意:这最后的操作顺序为您提供相同的结果,而不是error ~1e-14
。
编辑2:复制M2_Index_Dist
:
II = ndgrid(1:size(Matrix_2,1),1:size(Matrix_2,1));
M2_Index_Dist = [II(:) d(:)];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句