フィルターのクリア

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 回表示 (過去 30 日間)
For eg. [0.4 0.3 0.3] It should be generated randomly.
  2 件のコメント
Roger Stafford
Roger Stafford 2014 年 11 月 13 日
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?
Abhinav
Abhinav 2014 年 11 月 13 日
N value will vary in between 1 and 5

サインインしてコメントする。

採用された回答

Roger Stafford
Roger Stafford 2014 年 11 月 13 日
編集済み: Roger Stafford 2014 年 11 月 13 日
diff([0,sort(randi([0,10],1,N-1)),10])/10; % <-- Corrected
  4 件のコメント
Abhinav
Abhinav 2014 年 11 月 13 日
編集済み: Abhinav 2014 年 11 月 13 日
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 2014 年 11 月 13 日
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.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by