Clear Filters
Clear Filters

Pre Allocating for Speed

1 view (last 30 days)
Nathan McClean
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 Comments
Adam
Adam on 4 Apr 2019
Edited: Adam on 4 Apr 2019
p_hat = zeros( 1, length(Acc_g) );
for...
...
end
etc.
although you should not use length ideally - either use numel for vectors or size, with the dimensions you want for larger dimension arrays.
Also, you will end up with a 0 at the beginning of each of your arrays (or you can pre-allocate NaNs if you prefer) since you only start from n+1 for some reason.
Also note it is presumably a warning, not an error that you are getting, and that from the M-Lint code analysis, not on running the code. Still, these warnings should be heeded so you are correct to do so!
John D'Errico
John D'Errico on 4 Apr 2019
+1 for a pretty accurate answer by Adam.

Sign in to comment.

Answers (1)

Andreas Bernatzky
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.

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!