필터 지우기
필터 지우기

Rewriting a vector addition and multiplication.

조회 수: 4 (최근 30일)
hello_world
hello_world 2016년 8월 16일
답변: James Tursa 2016년 8월 16일
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:
D = sum(A.^2,2)(:,ones(1,N2)) + sum(B.^2,2)(ones(1,N1),:) - 2.*(A*B');
or perhaps something like this is even better:
D = sum[(A.^2,2)(:,ones(1,N2)) + (B.^2,2)(ones(1,N1),:) - . . .];
I know that above expression is wrong because one needs to store sum in a temporary variable before indexing. However, it is just for illustration purpose that I want to write down this expression in one single step.
I will appreciate any advise.

채택된 답변

Thorsten
Thorsten 2016년 8월 16일
편집: Thorsten 2016년 8월 16일
Repmat is your friend here:
D = repmat(sum(A.^2, 2), [1, N2]) + repmat(sum(B.^2, 2)', [N1, 1]) - 2*A*B';
or as a one-liner all together:
D = repmat(sum(A.^2, 2), [1, size(B, 1)]) + repmat(sum(B.^2, 2)', [size(A, 1), 1]) - 2*A*B';
  댓글 수: 1
Thorsten
Thorsten 2016년 8월 16일
편집: Thorsten 2016년 8월 16일
I'm pretty sure that it is not possible in Matlab you compute something and then index into the result, like
(A.^2,2)(:,ones(1,N2))
But I agree that this would be quite nice to have.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

James Tursa
James Tursa 2016년 8월 16일
D = bsxfun(@plus,sum(A.^2, 2),sum(B.^2, 2)') - 2.*(A*B');

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by