Uniformly distributed pseudo-random numbers
조회 수: 5 (최근 30일)
이전 댓글 표시
I am attempting to randomize a set of integers (1:12) and there are twelve of each number, for a total of 144 numbers. Basically I am trying to figure out if there is a way to randomize the numbers so that each number follows a previous number the same amount of times as other numbers (i this case 12 would follow 11 once, 12 would follow 10 once, 3 would follow 12 once) and so on.
Is there a somewhat easy way to go about this issue in matlab?
댓글 수: 0
채택된 답변
Roger Stafford
2014년 8월 27일
To do what you ask would require the result vector to have 145, not 144, elements, unless the vector is considered circular with the first element regarded as following the last element. In the following code you can have your choice since the last element in B always equals the first element. You can either leave B as is with its 145 elements or you can delete the last element, depending whether the vector is to be considered circular.
n = 12;
b = true;
while b
A = zeros(n);
B = zeros(n^2+1,1);
j = ceil(n*rand);
B(1) = j;
for k = 1:n^2
f = find(A(:,j)==0);
m = length(f);
if m == 0
break;
else
i = f(ceil(m*rand));
A(i,j) = k;
j = i;
B(k+1) = j;
end
end
b = any(any(A==0));
end
This is not highly efficient code since it continues to repeat the while loop until it succeeds in completing the vector B with the requested property. This usually takes a number of trials. When it succeeds, the vector B will have one occurrence of each possible pairing of successive elements, and since the 'rand' function is used in this placement, B can be considered random in a sense.
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Random Number Generation에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!