how to multiply a N*N*M matrix with 1*M array

2 views (last 30 days)
I have a matrix A with size N*N*M and array b with the size of 1*M.
I want to multiply the elements of i^th dimension of matrix A (i.e. A(:,:,i) ) with the i^th dimension of array b (i.e. b(1,i)). Meaning that: e.g.:
A(:,:,1)=[1 1; 1 1]
A(:,:,2)=[1 1; 1 1]
A(:,:,3)=[1 1; 1 1]
b=[1 2 3]
=> A times b
Results:
C(:,:,1)=[1 1; 1 1]
C(:,:,2)=[2 2; 2 2]
C(:,:,3)=[3 3; 3 3]
I am not looking for writing a loop and go through every single layer separately.
I was wondering if you guys know a fast way to do it. Thanks

Accepted Answer

Stephen23
Stephen23 on 31 May 2016
Edited: Stephen23 on 31 May 2016
This works correctly, and is fast and efficient:
A(:,:,1)=[1 1; 1 1];
A(:,:,2)=[1 1; 1 1];
A(:,:,3)=[1 1; 1 1];
b=[1 2 3];
bsxfun(@times,A,reshape(b,1,1,[]))

More Answers (1)

Walter Roberson
Walter Roberson on 31 May 2016
gpuarray() and pagefun() if you want fast ways of doing it.
Otherwise, writing a loop is going to have the best performance. You can hide the loop by using arrayfun() but that will be slower.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!