Finding a random non-zero location in a vector

조회 수: 8 (최근 30일)
Amit
Amit 2013년 12월 27일
댓글: Walter Roberson 2013년 12월 27일
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
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
Amit 2013년 12월 27일
Thank you, but I suspect that this will result in probably more poor performance in my case as first Rs is a growing vector (which grows to significantly larger size) and the ratio of zeros to nonzeros changes with every loop.
Walter Roberson
Walter Roberson 2013년 12월 27일
If Rs is a growing vector then you need to be careful because growing vectors can be slow.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by