3
votes


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.

2
What should be the output if l is not 1, i.e. if B is a matrix?Dirk

2 Answers

6
votes

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
2
votes

If I > 1, then you will have to reorder the dimensions of B first with a permute,

>> B = [100 10 1; 1 10 100];
>> C = bsxfun(@times, A, permute(B, [3 2 1]));
>> C

C(:,:,1) =

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


C(:,:,2) =

           1          20         300
           4          50         600
           7          80         900
          10         110        1200