Computing A(:, m)*B(m, :) without a for loop

조회 수: 1 (최근 30일)
Nicolas Perez
Nicolas Perez 2018년 11월 12일
댓글: Nicolas Perez 2018년 11월 12일
Provided I have two matrices A and B of dimensions NxM and MxN I want to compute a matrix C of dimensions NxNxM such that each NxN slice is the result of the prduct A(:, m)*B(m, :). I know this can be obtained in the following way:
for m=1:M
C(:, :, m) = A(:, m)*B(m, :);
end
Is there a way of obtaining the same result without using a for loop (with the aim of making the computation faster)?

채택된 답변

Matt J
Matt J 2018년 11월 12일
Ar=reshape(A,N,1,[]);
Br=reshape(B.',1,N,[]);
C=Ar.*Br;

추가 답변 (1개)

madhan ravi
madhan ravi 2018년 11월 12일
C(:, :, 1:M) = A(:, 1:M)*B(1:M, :);
  댓글 수: 1
Nicolas Perez
Nicolas Perez 2018년 11월 12일
The output of A(:, 1:M)*B(1:M, :); is the sum of C(:, :, 1:M) along the third dimension (an NxN matrix). Thus, you get the "Assignment has fewer non-singleton rhs dimensions than non-singleton subscripts" error.

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

카테고리

Help CenterFile Exchange에서 Chemistry에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by