bsxfun implementation in matrix multiplication

bsxfun, matlab, matrix, matrix-multiplication, performance

Solution

Send `x` to the third dimension, so that singleton expansion would come into effect when `bsxfun` is used for multiplication with `A`, extending the product result to the third dimension. Then, perform the `bsxfun` multiplication -

val = bsxfun(@times,A,permute(x,[3 1 2])) 

Now, `val` is a `3D` matrix and the desired output is expected to be a `2D` matrix concatenated along the columns through the third dimension. This is achieved below -

out = reshape(permute(val,[1 3 2]),size(val,1)*size(val,3),[])

Hope that made sense! Spread the `bsxfun` word around! woo!! :)

Problem

As always trying to learn more from you, I was hoping I could receive some help with the following code. I need to accomplish the following: 1) I have a vector: ``` x = [1 2 3 4 5 6 7 8 9 10 11 12] ``` 2) and a matrix: ``` A =[11 14 1 5 8 18 10 8 19 13 20 16] ``` I need to be able to multiply `each` value from `x` with `every` value of `A`, this means: ``` new_matrix = [1* A 2* A 3* A ... 12* A] ``` This will give me this `new_matrix` of size `(12*m x n)` assuming `A (mxn)`. And in this case `(12*4x3)` How can I do this using `bsxfun` from matlab? and, would this method be faster than a `for-loop`? Regarding my `for-loop`, I need some help here as well... I am not able to storage each `"new_matrix"` as the loop runs :( ``` for i=x new_matrix = A.*x(i) end ``` Thanks in advance!! EDIT: After the solutions where given First solution ``` clear all clc x=1:0.1:50; A = rand(1000,1000); tic val = bsxfun(@times,A,permute(x,[3 1 2])); out = reshape(permute(val,[1 3 2]),size(val,1)*size(val,3),[]); toc ``` Output: ``` Elapsed time is 7.597939 seconds. ``` Second solution ``` clear all clc x=1:0.1:50; A = rand(1000,1000); tic Ps = kron(x.',A); toc ``` Output: ``` Elapsed time is 48.445417 seconds. ```

Original source

Related problems