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.

For eg. [0.4 0.3 0.3] It should be generated randomly.

2 Comments

If N is large, restricting the array values to one decimal place only would force many of the values to be zero if I understand you correctly. Are you sure this is what you want?

Sign in to comment.

 Accepted Answer

diff([0,sort(randi([0,10],1,N-1)),10])/10; % <-- Corrected

4 Comments

x=diff([0,sort(randi([0,10],5-1)),10])/10 Error using horzcat Dimensions of matrices being concatenated are not consistent.
Getting this error. BTW thanks for showing interest in my problem :)
I have made a correction on my answer above. The output of 'randi' here should be a 1*by*N-1 row vector.
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.
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

Community Treasure Hunt

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

Start Hunting!