Tuesday, October 3, 2017

Matlab: Elementwise multiply a 1D vector or a 2D matrix with each slice of a 3D Matrix

I know that an answer to this can be found in many websites like stackoverflow, and actually I am referring to one that has the answer here too. The thing is sometimes having a different wording may help others in search. Also for me as writing about it here will help me memorize and return back to it when needed :)

Matlab is a great tool for numerical computation, but many tricks may be hard to get used too, one of the main features in MATLAB is factorization and using functions like "bsxfun"

I came across a problem that required me to multiply a 2d Matrix by each slice of a 3D matrix, the regular solution for this is to do a For loop and do a simple element wise multiplication for each 2D slice of the 3D Matrix.

another solution is to use "bsxfun" and "permute":

So Assuming you have a matrix A with 3x4 dimensions and a matrix B with 3x4x5 dimensions, you can use :
result = bsxfun(@times, A, B);

or if  you have a vector of A of 5 cells and a matrix B with 3x4x5 dimensions, you can use :
Use bsxfun with permute to align dimensions:

result = bsxfun(@times, permute(vec1,[2 3 1]), mat2);

the original link that I had this solution from is in stackoverflow

No comments:

Post a Comment