Finding a random non-zero location in a vector
이전 댓글 표시
I have a vector (Rs, size n x 1) which has few zeros and rest nonzero values. I need to randomly find a index to a nonzero valued location in the vector. This need to be done in a loop where every loop will change the number of zeros and nonzeros in the vector.
I have been attempting to do this in following fashion:
loop start
toPick = find(Rs);
rand_pick = toPick(randi(numel(toPick)));
- Do something which changes the no. of zeros and nonzeros in Rd -
end
This method works. However the issue is the size of toPick changes which can result in significant overhead in terms of performance. Is there a way to change the code to increase the performance?
답변 (1개)
Walter Roberson
2013년 12월 27일
When the probability of "success" is not too small, sometimes the fastest is the rejection method.
numRs = size(Rs,1); %can be done before any looping
while true
rand_pick = Rs(randi(numRs));
if rand_pick > 0; break; end
end
You can also increase the speed of this by choosing the random numbers ahead of time:
num_repeats = 1000; %supposing the code loop as a whole is to be executed 1000 times
ridx = randi(numRs, [2*num_repeats, 1]); %if you know the average fill rate you can adjust the "2*" using statistical techniques
num_left = size(ridx,1);
for K = 1 : num_repeats
while num_left > 0
rand_pick = Rs(ridx(num_left));
num_left = num_left - 1;
if rand_pick > 0; break; end
end
if num_left <= 0; error('need a bigger random buffer'); end
do something with rand_pick
end
댓글 수: 2
Amit
2013년 12월 27일
Walter Roberson
2013년 12월 27일
If Rs is a growing vector then you need to be careful because growing vectors can be slow.
카테고리
도움말 센터 및 File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!