필터 지우기
필터 지우기

Elemental matrix multiplication [NxN] and [1xn] into [NxNxn]

조회 수: 3 (최근 30일)
William
William 2014년 3월 31일
댓글: William 2014년 3월 31일
Hi,
I want to multiply every element in A[NxN] by every value in B[1xn] to get C[NxNxn]
Current code:
for i = 1:n
c(:,:,i) = b(i) * a(:,:)
end
Is it possible to do this without the for loop to make it run faster?
Many thanks,

채택된 답변

Azzi Abdelmalek
Azzi Abdelmalek 2014년 3월 31일
편집: Azzi Abdelmalek 2014년 3월 31일
a=rand(4,3)
b=rand(1,6)
[n,m]=size(a)
p=numel(b);
c=reshape(bsxfun(@times, repmat(a(:)',numel(b),1),b')',n,m,p)
  댓글 수: 2
John D'Errico
John D'Errico 2014년 3월 31일
편집: John D'Errico 2014년 3월 31일
That seems overly difficult the way you did it. Cleaner is just to reshape B first, THEN use bsxfun. No need at all to use repmat!
C = bsxfun(@times,A,reshape(B,[1,1,numel(B)]));
The idea is that BSXFUN will implicitly replicate as necessary those dimensions that are singleton (i.e., have a 1 in them.)
William
William 2014년 3월 31일
That's great, faster now. Many thanks

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

추가 답변 (0개)

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by