Finding a random non-zero location in a vector
8 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(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 个评论
Walter Roberson
2013-12-27
If Rs is a growing vector then you need to be careful because growing vectors can be slow.
另请参阅
类别
在 Help Center 和 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!