Finding a random non-zero location in a vector
4 views (last 30 days)
Show older comments
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?
0 Comments
Answers (1)
Walter Roberson
on 27 Dec 2013
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 Comments
Walter Roberson
on 27 Dec 2013
If Rs is a growing vector then you need to be careful because growing vectors can be slow.
See Also
Categories
Find more on Creating and Concatenating Matrices in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!