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

element matrix multiplication

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,

Best Answer

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)
Related Question