Reputation: 316
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.
Upvotes: 3
Views: 890
Reputation: 14939
C=bsxfun(@times,A,B)
C =
100 20 3
400 50 6
700 80 9
1000 110 12
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
Upvotes: 6
Reputation: 4551
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
Upvotes: 2