Preallocating for speed?

1 visualizzazione (ultimi 30 giorni)
Ruben Dario Ramirez Serna
Ruben Dario Ramirez Serna il 14 Mar 2022
Risposto: Rik il 14 Mar 2022
Hello. The variables that I indicate with the red arrow, how do I modify the speed? what function in matlab is it?

Risposte (1)

Rik
Rik il 14 Mar 2022
When you append data to a variable like this:
a=[1 2 3];
a=[a 4];
Matlab first allocates a block of memory large enough to hold 4 numbers, then it copies the data from the first array to the second array, then writes the new element to that new array. After that the memory for the first array is released.
If you do this often, that means you're copying a lot of data around, which takes time. What you can do instead is to create an array before you start the loop. This array is large enough to hold most or all the data you expect to encounter.
a=zeros(1,4);
for n=1:4
a(n)=n;
end
a
a = 1×4
1 2 3 4
This allocates memory only once and removes the need of copying the data over and over again. Because you do this before using it, this strategy is called pre-allocation.
You can also use this strategy if you don't know the expected number of elements:
a=zeros(1,4);
n=0;
while rand<0.75
n=n+1;
a(n)=n;
end
% remove unused elements
% this will not do anything if n>=numel(a)
a((n+1):end)=[];
a
a = 1×5
1 2 3 4 5

Categorie

Scopri di più su Characters and Strings 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