# Pre Allocating for Speed

14 views (last 30 days)
Nathan McClean on 4 Apr 2019
Hi,
My Matlab code comes up with an error regaring pre-allocating for speed. Would anybody be able to help me preallocate the following:
An example would be nice.
Thanks
%% Newmarks Method
a1=(1/(beta*dt^2))+((gamma/(beta*dt))*2*zeta*w_n);
a2=(1/(beta*dt))+(((gamma/beta)-1)*2*zeta*w_n);
a3=((1/(2*beta))-1)+((dt*2*zeta*w_n)*((gamma/(2*beta))-1));
wn_2=(w_n)^2+a1;
u_t(1)=0;
dudt(1)=0;
d2udt2(1)=0;
for n=1:length(Acc_g)-1
p_hat(n+1)=(Acc_g(n+1))+(a1*u_t(n))+(a2*dudt(n))+(a3*d2udt2(n));
u_t(n+1)=p_hat(n+1)/wn_2;
dudt(n+1)=((gamma/(beta*dt))*(u_t(n+1)-u_t(n)))+((1-(gamma/beta))*dudt(n))+(dt*(1-(gamma/(2*beta)))*d2udt2(n));
d2udt2(n+1)=((1/(beta*dt^2)))*(u_t(n+1)-u_t(n))-((1/(beta*dt))*dudt(n))-(((1/(2*beta))-1)*d2udt2(n));
end
##### 2 CommentsShowHide 1 older comment
John D'Errico on 4 Apr 2019
+1 for a pretty accurate answer by Adam.

Andreas Bernatzky on 4 Apr 2019
Hey Nathan,
if a vector is not preallocated it means that it grows in every Iteration.
This means you have to expand your vector, shift all the entries and shrink it back. Long Story short unnecessary memory usage. Here a small example:
%% Vector without preallocating
loops=20;
Vector1=[];
for(a=1:1:loops)
Vector1(end+1)=a;
end
%% Vector with preallocating
loops=20;
Vector2=ones(1,loops);
for(a=1:1:loops)
Vector2(a)=a;
end
Especially for your example preallocate your vector with ones or zero (depends on the application).
In your example i did it for p_hat.
%% Newmarks Method
a1=(1/(beta*dt^2))+((gamma/(beta*dt))*2*zeta*w_n);
a2=(1/(beta*dt))+(((gamma/beta)-1)*2*zeta*w_n);
a3=((1/(2*beta))-1)+((dt*2*zeta*w_n)*((gamma/(2*beta))-1));
wn_2=(w_n)^2+a1;
u_t(1)=0;
dudt(1)=0;
d2udt2(1)=0;
p_hat=ones(1,length(Acc_g)-1);
for n=1:length(Acc_g)-1
p_hat(n)=(Acc_g(n+1))+(a1*u_t(n))+(a2*dudt(n))+(a3*d2udt2(n));
u_t(n+1)=p_hat(n+1)/wn_2;
dudt(n+1)=((gamma/(beta*dt))*(u_t(n+1)-u_t(n)))+((1-(gamma/beta))*dudt(n))+(dt*(1-(gamma/(2*beta)))*d2udt2(n));
d2udt2(n+1)=((1/(beta*dt^2)))*(u_t(n+1)-u_t(n))-((1/(beta*dt))*dudt(n))-(((1/(2*beta))-1)*d2udt2(n));
end
Hope I could help.

R2018b

### Community Treasure Hunt

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

Start Hunting!

Translated by