Filter löschen
Filter löschen

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 Ansicht (letzte 30 Tage)
randi(10,6,6)

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 19 Okt. 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 Kommentare
rashmi am
rashmi am am 20 Okt. 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 am 20 Okt. 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.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Matrices and Arrays finden Sie in Help Center und File Exchange

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by