MATLAB Answers

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

461 views (last 30 days)
William on 31 Mar 2014
Commented: William on 31 Mar 2014
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(:,:)
Is it possible to do this without the for loop to make it run faster?
Many thanks,


Sign in to comment.

Accepted Answer

Azzi Abdelmalek
Azzi Abdelmalek on 31 Mar 2014
Edited: Azzi Abdelmalek on 31 Mar 2014
c=reshape(bsxfun(@times, repmat(a(:)',numel(b),1),b')',n,m,p)


John D'Errico
John D'Errico on 31 Mar 2014
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.)

Sign in to comment.

More Answers (0)

Sign in to answer this question.

Translated by