Setting array elements to zero, the best way

38 visualizzazioni (ultimi 30 giorni)
Hello all,
I'm writing a for loop with a large number of iterations in it. And at the end of each itaration, I have to set a large array elements to zero. I can do it in the following way:
for i=1:1:LARGE_NUMBER
array = zeros(1, ANOTHER_LARGE_NUMBER);
% do stuff here with the now zero array
end
However, it looks like to me that this will allocate the memory over and over again at each iteration, which will be a huge performance hit due to the large number of iterations. I can also do this:
array = zeros(1, ANOTHER_LARGE_NUMBER);
for i=1:1:LARGE_NUMBER
array(:) = 0;
% do stuff here with the now zero array
end
But I'm not sure how this is implemented in MATLAB. Is this the most efficient way of making everything zero in MATLAB?
For instance, it's possible to do the following in C language:
memset(array, 0, sizeof(int) * ANOTHER_LARGE_NUMBER);
Which will efficiently set all values to zero. Is there any equivalent efficient method to do the same in MATLAB?
Any advice will be appreciated.
  2 Commenti
KSSV
KSSV il 5 Feb 2019
Have a look on Sparse
madhan ravi
madhan ravi il 5 Feb 2019
But according to the preallocation all the elements are zeros right? Why do you have to do
array(:) = 0; %?

Accedi per commentare.

Risposta accettata

Stephen23
Stephen23 il 5 Feb 2019
Modificato: Stephen23 il 5 Feb 2019
Use
array(:) = 0;
at the start of the loop. This will not require new arrays to be created, which is likely faster... but the only way to tell for sure about the speed is to profile your code:
"But I'm not sure how this is implemented in MATLAB. Is this the most efficient way of making everything zero in MATLAB?"
And that is the point. MATLAB is a high-level language, and it performs a lot of optimizations and code acceleration when the code is compiled (at runtime), but the documentation and advice from TMW (the makers of MATLAB) is that users should not rely on a specific method performing specific low-level operations, and should instead focus on writing clear code following the guidelines provided:
For this reason you should use array(:)=0, because:
  1. it is shorter and simpler,
  2. it makes it clear that you simply want to set all of array's values to zero, whatever size array might have,
  3. it uses a preallocated array, which is considered best-practice.

Più risposte (0)

Tag

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by