2.51 generate random matrix so that each row adds to 1

2.51.1 Mathematica
2.51.2 Matlab
2.51.3 Maple

Generate the random matrix and divide each row by its total

2.51.1 Mathematica

mat = Table[RandomReal[],{3},{4}]
 

\[ \left ( \begin {array}{cccc} 0.76862 & 0.917299 & 0.606119 & 0.63735 \\ 0.610077 & 0.208307 & 0.0337861 & 0.473017 \\ 0.388772 & 0.432688 & 0.475881 & 0.68523 \\ \end {array} \right ) \]

s   = Total[mat,{2}]
 

{1.15201, 1.99068, 3.05063}

s   = Total[mat,{2}]; 
b   = mat/s
 

\[ \left ( \begin {array}{cccc} 0.15919 & 0.0553157 & 0.448352 & 0.337142 \\ 0.358594 & 0.264968 & 0.123659 & 0.25278 \\ 0.216269 & 0.248665 & 0.278871 & 0.256195 \\ \end {array} \right ) \]

Total[b,{2}]
 

Out[24]= {1.,1.,1.}
 

 

2.51.2 Matlab

A = rand(3,4) 
s = sum(A,2); 
B = bsxfun(@rdivide,A,s) 
sum(B,2)
 

A = 
 0.6787    0.3922    0.7060    0.0462 
 0.7577    0.6555    0.0318    0.0971 
 0.7431    0.1712    0.2769    0.8235 
 
B = 
 0.3723    0.2151    0.3873    0.0253 
 0.4913    0.4250    0.0206    0.0630 
 0.3689    0.0850    0.1375    0.4087 
 
ans = 
    1.0000 
    1.0000 
    1.0000
 

 

2.51.3 Maple

restart; 
A:=LinearAlgebra:-RandomMatrix(3,4,generator=0..1.0 ); 
for n from 1 to LinearAlgebra:-RowDimension(A)  do 
   A[n,..]:=A[n,..]/add(A[n,..]); 
od: 
A; 
 
#verify each row sums to 1 
map(x->add(x),[LinearAlgebra:-Row(A,[1..-1])])
 

      [0.9705927818  0.9575068354  0.0975404050  0.1269868163] 
      [                                                      ] 
 A := [0.1576130817  0.5468815192  0.6323592462  0.9057919371] 
      [                                                      ] 
      [0.9648885352  0.2784982189  0.9133758561  0.8147236864] 
 
    [0.4508876154  0.4448085560  0.0453122684  0.0589915605] 
    [                                                      ] 
    [0.0702799715  0.2438555046  0.2819701848  0.4038943392] 
    [                                                      ] 
    [0.3247157951  0.0937235414  0.3073801341  0.2741805296] 
 
 
     [1.00000000026568, 1.00000000004739, 1.00000000023679]