Clear Filters
Clear Filters

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 view (last 30 days)
randi(10,6,6)

Accepted Answer

Walter Roberson
Walter Roberson on 19 Oct 2015
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 Comments
rashmi am
rashmi am on 20 Oct 2015
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 on 20 Oct 2015
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Products

Community Treasure Hunt

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

Start Hunting!