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?
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?
You can speed it up further by using 2D matrix operations as follows:
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.
Approach
I first converted both input matrices into 2D matrices using reshape (taking first and second dimension together):
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:
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.