Vectorizing a Simple(?) Operation

25 visualizzazioni (ultimi 30 giorni)
bil
bil il 9 Set 2024
Commentato: bil il 12 Set 2024
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 Commenti
Mike Croucher
Mike Croucher il 11 Set 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
bil
bil il 12 Set 2024
Hi Alan and Mike, thanks for the helpful comments. One way I have found to circumvent the for-loop is by circshifting my array backwards and forwards by 1, and then performing an XOR gate. This effectively performs the same logic as what I wanted in the for-loop and also preserves the number of walls.

Accedi per commentare.

Risposte (0)

Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by