Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiply each value in rows of Matrix A by each corresponding value of a specfic row in Matrix B


I have a A=[m,n] matrix and a B=[n,l] matrix.

A =
[1     2     3   
 4     5     6   
 7     8     9   
 10    11    12]

For the sake of simplicity, let's assume l=1, so B is in fact a vector B=[n,1]

B =   [100    10     1]

I would like multiply all the values in each row of A by a corresponding value of B - column-wise.

I know how to do it "manually":

C=[A(:,1)*B(:,1), A(:,2)*B(:,2), A(:,3)*B(:,3)]

This is the result I want:

C = [100          20           3  
     400          50           6  
     700          80           9  
     1000         110          12]

Unfortunately my real life matrices are a bit bigger e.g. (D=[888,1270]) so I'm looking for smarter/faster way to do this.

like image 991
kategorically Avatar asked Jan 29 '26 01:01

kategorically


1 Answers

Pre R2016b:

C=bsxfun(@times,A,B)

C =
     100          20           3
     400          50           6
     700          80           9
    1000         110          12

R2016b and later:

In MATLAB® R2016b and later, you can directly use operators instead of bsxfun , since the operators independently support implicit expansion of arrays.

C = A .* B
like image 187
Stewie Griffin Avatar answered Jan 31 '26 02:01

Stewie Griffin