1

i want to create a matrix that each row of the matrix have 7 real random number in [0,1] and the sum of number in each rows should be equal to 1. this matrix have 100 rows and 7 columns. how can i do it? at first ,i create an array with 1 row and 7 columns. then write the code as bellow. i try normal the number in the rows but sum of each row became more than 1.how can i fix it? thank for taking your time.

a = rand(1,7);
for i=1:7
a(i) = a(i)/sum(a);
end
sum(a)
hsi
  • 97
  • 1
  • 11
  • 2
    If you additionally want each row to be _uniformly distributed_ (you don't specify) you need an approach like [this](https://stackoverflow.com/q/8064629/2586922). Generating statistically independent samples and dividing by the obtained sum won't work – Luis Mendo Jul 06 '17 at 10:28
  • @LuisMendo I was just about to write the same thing – Vahe Tshitoyan Jul 06 '17 at 10:31

2 Answers2

4

For 100 by 7, you can use bsxfun:

a = rand(100,7);
a = bsxfun(@rdivide,a.',sum(a.')).';

Here the sum of each row = 1

Yacine
  • 321
  • 2
  • 15
2

The problem is that by using a for-loop, you're changing the sum of the vector every loop iteration. You should take advantage of MATLAB's ability to act on whole matrices at once:

a = rand(1,7);
a = a./sum(a);
MrAzzaman
  • 4,734
  • 12
  • 25