How to generate a random array of 1*N matrix in which sum of all elements is 1 and numbers generate should be upto 1 decimlal place only.

2 views (last 30 days)
For eg. [0.4 0.3 0.3] It should be generated randomly.

Accepted Answer

Roger Stafford
Roger Stafford on 13 Nov 2014
Edited: Roger Stafford on 13 Nov 2014
diff([0,sort(randi([0,10],1,N-1)),10])/10; % <-- Corrected
  4 Comments
Abhinav
Abhinav on 13 Nov 2014
Edited: Abhinav on 13 Nov 2014
Thanks a lot. I have one small issue with it. Sometimes it is assigning 0 to an element. I don't want 0 in my array. Any non zero number is acceptable. And if you can explain the code, it will be very helpful.
Roger Stafford
Roger Stafford on 13 Nov 2014
To avoid zeros you can do this, Abhinav:
x = (diff([0,sort(randi([0,10-N],1,N-1)),10-N])+ones(1,N))/10;
Note that with this restriction, N cannot be greater than 10. Otherwise there will be error messages.
As for an explanation, first, if your N numbers are each multiplied by ten, then they are integers and their sum must always be 10, which explains the division by 10 at the last step. Next, if 1 is subtracted from each integer, then their sum is 10-N, and they range from 0 to 10-N, which explains the addition of "ones(1,N)".
So now the equivalent problem is to find random integers ranging from 0 to 10-N whose sum is 10-N. The call "randi([0,10-N],1,N-1)" gives N-1 integers in this range and 'sort' arranges them in ascending order. The row vector
[0,sort(randi([0,10-N],1,N-1)),10-N]
consists of N+1 ascending integers which start with 0 and end with 10-N. If we perform a 'diff' on these, the resulting integers will all necessarily have a sum of 10-N because 0 and 10-N are the two end values of that vector. Also all the resulting integer differences must lie between 0 and 10-N. That is what was required in the above equivalent version. Therefore problem solved.
To get a better feeling for this solution you can separate out the parts of the code:
t1 = randi([0,10-N],1,N-1);
t2 = sort(t1);
t3 = [0,t2,10-N];
t4 = diff(t3);
t5 = t4 + ones(1,N);
t6 = t5/10;
and experiment with each step of the computation to see how it proceeds to a solution.

Sign in to comment.

More Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!