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 visualizzazioni (ultimi 30 giorni)
For eg. [0.4 0.3 0.3] It should be generated randomly.
  2 Commenti
Roger Stafford
Roger Stafford il 13 Nov 2014
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?

Accedi per commentare.

Risposta accettata

Roger Stafford
Roger Stafford il 13 Nov 2014
Modificato: Roger Stafford il 13 Nov 2014
diff([0,sort(randi([0,10],1,N-1)),10])/10; % <-- Corrected
  4 Commenti
Abhinav
Abhinav il 13 Nov 2014
Modificato: Abhinav il 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 il 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.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by