Borrar filtros
Borrar filtros

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.

1 visualización (últimos 30 días)
For eg. [0.4 0.3 0.3] It should be generated randomly.
  2 comentarios
Roger Stafford
Roger Stafford el 13 de Nov. de 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?

Iniciar sesión para comentar.

Respuesta aceptada

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

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Creating and Concatenating Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by