简体   繁体   English

在MATLAB中加速特殊情况的欧式距离

[英]Speed-up special case euclidean distance in MATLAB

I want to optimize the following code example: 我想优化以下代码示例:

%Example definition
A = rand(40,10000,250);
B = rand(40,10000,250);

%Euclidean
seuc = sum((A-B).^2, 3);

Do you have any idea how to speed this up? 您知道如何加快速度吗? Or is it already optimized for MATLAB? 还是已经为MATLAB优化过?

You can speed it up further by using 2D matrix operations as follows: 您可以通过如下使用2D矩阵运算来进一步加快速度:

reshape(sum((reshape(A, [], size(A, 3))-reshape(B, [], size(A, 3))).^2, 2), size(A, 1), size(A, 2))

This reduces the execution time from ~0.5s to ~0.3s. 这将执行时间从〜0.5s减少到〜0.3s。

Approach 途径

I first converted both input matrices into 2D matrices using reshape (taking first and second dimension together): 我首先使用重塑将两个输入矩阵转换为2D矩阵(将第一维和第二维放在一起):

reshape(A, [], size(A, 3))
reshape(B, [], size(A, 3))

At the end, I reshaped the outcome of the sum (a 1D vector) back into the desired 2D vector: 最后,我将总和的结果(一个1D向量)重塑为所需的2D向量:

reshape(..., size(A, 1), size(A, 2))

Why is this faster? 为什么这样更快?

I don't know for sure. 我不确定 I guess MATLAB more often used with 2D matrices than 3D matrices and therefore better optimised for it. 我猜想MATLAB比2D矩阵更常用于2D矩阵,因此可以更好地对其进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM