Manipulation of matrix addition and multiplication.

2 visualizaciones (últimos 30 días)
hello_world
hello_world el 16 de Ag. de 2016
Comentada: the cyclist el 18 de Ag. de 2016
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.
  3 comentarios
the cyclist
the cyclist el 16 de Ag. de 2016
Also, this equivalent formulation seems closer to your prototype formula, but I still don't quite see a simpler set of matrix operations to get you there:
D = bsxfun(@plus,diag(A*A'),diag(B*B')') - 2.*(A*B')
(I think this version is likely more computationally intensive, but somewhat more elegant.)
James Tursa
James Tursa el 16 de Ag. de 2016
Editada: James Tursa el 16 de Ag. de 2016
How is this different from this earlier post which was already answered?

Iniciar sesión para comentar.

Respuesta aceptada

Matt J
Matt J el 16 de Ag. de 2016
Editada: Matt J el 16 de Ag. de 2016
Bp=permute(B,[3,2,1]);
D=reshape( sum(bsxfun(@minus, A, Bp).^2,2)) , N1,N2);
  5 comentarios
Matt J
Matt J el 18 de Ag. de 2016
Well... permutes are expensive as compared to reshapes. I was seeking to minimize them. It is possible to do this entirely without permutes/transposes if the OP had organized the 3x1 vectors in matrix columns instead of matrix rows.
the cyclist
the cyclist el 18 de Ag. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Resizing and Reshaping Matrices en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by