Given a row of the same number of values as the number of columns in a matrix, how to scale each column by the corresponding value in that row? This picture explains more the problem
In Matlab, bsxfun is used.
credit for this solution goes to Bob Hanlon, Adriano Pascoletti, Kurt Tekolste, David Park, and Peter. J. C. Moses from the Math group
r = {2,3}; mat = {{1,2},{3,4},{5,6}}; r #&/@mat (*or*) Map[v*#&, mat]
{{2, 6}, {6, 12}, {10, 18}}
Another way is to use Inner[] command. Credit for this solution goes to Sswziwa Mukasa and Peter. J. C. Moses from the Math group
r={2,3}; mat={{1,2},{3,4},{5,6}}; Inner[Times,mat,r,List]
Out[66]= {{2, 6}, {6, 12}, {10, 18}}
r=[2 3]; A=[1 2; 3 4; 5 6] bsxfun(@times,r,A)
ans = 2 6 6 12 10 18
program t45 implicit none integer, parameter :: nRow=3, nCol=2 character(len=*), parameter :: FMT = "(2I5)" integer :: v(nCol),A(nRow,nCol),B(nRow,nCol),i,j; !-- initialization of data v = [2,3] A(1,:) = [1,2]; A(2,:) = [3,4]; A(3,:) = [5,6]; !F2008 !do concurrent (j = 1:nCol) ! B(:,j) = v(j)*A(:,j) !end do do j=1,nCol B(:,j) = v(j)*A(:,j) end do write(*,FMT) ( (B(i,j),j=1,nCol), i=1,nRow) end program t45
#compile and run >gfortran -std=f2008 t45.f90 >./a.out 2 6 6 12 10 18
r .* A
r:=Vector[row]([2,3]); mat:=Matrix([[1,2],[3,4],[5,6]]); f:=n->r(n)*mat(1..3,n); f~([1,2]); convert(%,Matrix)
\[ \left [ \begin {array}{cc} 2&6\\ \noalign {\medskip }6&12 \\ \noalign {\medskip }10&18\end {array} \right ] \]