Vectorizing a Simple(?) Operation
25 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi all,
This might be a bit of a fruitless question but I just want to confirm there is no other method. I want to know if there is any way of vectorizing the following code:
array = [1,0,1,1,0,0,1];
for i = 2:length(array)-1
if array(i-1) ~= array(i+1)
% Generate a random bit (0 or 1)
random_bit = randi([0, 1]);
% Update the array in place
array(i) = mod(array(i) + random_bit, 2);
end
end
The array can be of any length as long as it is only fillled with 0s and 1s. The key part of the code is that I want to update the array by doing nearest neighbor checks and in such a way that the number of walls (array(i) ~= array(i+1) for i from 1 to size(array)) is constant. And it is this constrained logic of my code that leads me to believe I cannot do away with using for-loops.
The reason I wish to vectorize the code is because I will be doing monte-carlo sampling where I have a large number of these arrays and wish to update them all at the same time using the above update rule, so in the ideal scenario I wouldn't have to use a nested for-loop to cycle through each sample.
3 commentaires
Mike Croucher
le 11 Sep 2024
Hi Bil
I assume you are thinking about vectorisation because you are concerned about speed. Thanks to JIT compilation, For-loops can be pretty fast these days in many cases. My suggestion would be to write the code as loops, see how the performance is and if it's a problem see what can be done about it.
While its true that a vectorised version may be faster, it's also possible that it won't be.
Write the code however you think in the first instance. Fix it if it needs fixing.
With that said, it IS slow to generate random numbers one at a time like that. I'd think about generating a vector of them at a time outside of the loop and then consume them in the loop.
Cheers,
Mike
Réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!