I have a matrix $A=\{a_{ij}\}$ of dimensions $n$ rows by $m$ columns, and I would like to multiply each row of the matrix by a constant $b_i$, $i=1,\ldots,n$, and store the result in the same variable. In linear-algebra speak, I basically would like to do $A=\mathrm{diag}(b_1,\ldots,b_n) A$. However, I would like to avoid having to create a diagonal matrix off the vector $(b_1,\ldots,b_n)$, because $n$ is large and I wouldn't want to use any more RAM. Is there a different and less memory demanding way to do $A=\mathrm{diag}(b_1,\ldots,b_n) A$?
My approach is to go over the rows of $A$ and multiply each by the respective element of the vector $(b_1,\ldots,b_n)$. May be there is a more elegant way to do this? By "elegant" I mean faster yet not too memory-demanding.
m = 3;
n = 5;
A = Table[RandomInteger[{0, 5}], {i, m}, {j, n}];
b = Table[RandomInteger[{5, 10}], {i, m}];
A
Print[b];
(* Standard Linear-Algebraic Solution *)
b=DiagonalMatrix[b];
cc=Dot[b,A];
cc
(* Less memory demanding solution *)
For[i = 1, i <= m, i += 1,
A[[i, All]] = b[[i]]*A[[i, All]];
];
A
SparseArray[]
for the diagonal matrix:SparseArray[Band[{1, 1}] -> b].A
. However, due to listability, even a Hadamard product suffices:b A
. $\endgroup$