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)
2
  • 2
    If you additionally want each row to be uniformly distributed (you don't specify) you need an approach like this. Generating statistically independent samples and dividing by the obtained sum won't work Commented Jul 6, 2017 at 10:28
  • @LuisMendo I was just about to write the same thing Commented Jul 6, 2017 at 10:31

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.