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 CenterFile Exchange 中查找有关 Matrices and Arrays 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by