Manipulation of matrix addition and multiplication.

1 view (last 30 days)
Hello Friends,
I have the following:
A = [1 2 3; 4 5 6; 7 8 9];
B = [10 11 12; 13 14 15];
[N1, D1] = size(A);
[N2, D2] = size(B);
A_sq = sum(A.^2, 2);
B_sq = sum(B.^2, 2)';
D = A_sq(:,ones(1,N2)) + B_sq(ones(1,N1),:) - 2.*(A*B');
where D is N1 x D1 matrix.
I want to write expression for D in one single step, i.e., something like this (this is for illustration purpose, but it should compute the same Euclidean distance as the code above):
D = sum(X - C).^2;
I will appreciate any advise.

Sign in to comment.

Accepted Answer

Matt J
Matt J on 16 Aug 2016
Edited: Matt J on 16 Aug 2016
D=reshape( sum(bsxfun(@minus, A, Bp).^2,2)) , N1,N2);
the cyclist
the cyclist on 18 Aug 2016
I repmat'ed his matrices to make them pretty huge, and found nearly identical timing for the reshape algorithm and the permute algorithm.
Interestingly, my original solution (in the comments)
D = bsxfun(@plus,sum(A.^2, 2),sum(B'.^2, 1)) - 2.*(A*B');
absolutely crushed both of these in timing.
So, as always, best to try to solve the problem (multiple ways if possible!), and then do optimization.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!