필터 지우기
필터 지우기

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