I know the below instruction gives a matrix of 6 by 6 which has numbers from 1 to 10 . But if i want to limit the numbers ,like if i want 1 to come in matrix thrice, two repeat 10 times so on .how do i do that?

1 回表示 (過去 30 日間)
randi(10,6,6)

採用された回答

Walter Roberson
Walter Roberson 2015 年 10 月 19 日
If you know the exact number of times you want each item to occur, then you create a vector with as many copies as should occur, then randomize the order of the vector and reshape the result to 6 x 6
v = [1 * ones(1,3), 2 * ones(1,10), 3 * ones(1,7), ... 10 * ones(1,4)];
reshape( v(randperm(v)), 6, 6)
  2 件のコメント
rashmi am
rashmi am 2015 年 10 月 20 日
yes, this works. But,when i am creating a bigger matrix,say 60 by 10 ,it is difficult to enter all the values. i want to limit one or two values and fill other blank spaces by some random number. how to i do that ?
Walter Roberson
Walter Roberson 2015 年 10 月 20 日
source_vals = 1 : 10; %what are we drawing from?
target_size = [60 10];
target_numel = prod(target_size);
v1 = [1 * ones(1,3), 2 * ones(1,10)]; %special cases, 3 1's, 10 2's
other_vals = setdiff(source_set, v1);
v2 = other_vals( randi(length(other_vals), 1, target_numel - length(v1) );
v = [v1, v2];
result = reshape( v(randperm(target_numel)), target_size );
This code is designed so that the numbers you give for the special case in v1 are exact numbers of occurrences. The remaining elements will be filled only from the elements not mentioned in v1.

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

その他の回答 (0 件)

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by