MATLAB: Nearly identical code, hugely different runtimes

optimizationstrange run errors

Hi all,
I've got a weird situation going on. I have the following code:
if true
for ii = 2:natom
tcheck = 1;
while tcheck ~= 0
tcheck = 0;
lx = rand*lxmax;
ly = rand*lymax;
lz = rand*lzmax;
for jj = 1:ii-1
x12 = lx-x(jj);
y12 = ly-y(jj);
z12 = lz-z(jj);
%

x12 = x12-lxmax* round(x12/lxmax);
y12 = y12-lymax* round(y12/lymax);
z12 = z12-lzmax* round(y12/lzmax);
%
dist = sqrt(x12^2 +y12^2 + z12^2);
if dist <= rmax
tcheck =tcheck +1;
break
end
end
end
x(ii) = lx;
y(ii) = ly;
z(ii) = lz;
ii
endif true
natom=4000 and x,y,z are vectors of length 4000. lxmax, lymax, and lzmax are all equal at 40.5 which is what I have "cubesize" set to in the next code. In general you can assume the parameters controlling the iteration process are the same for both.
I am trying to incorporate this code into another program and rewrote it as such:
if true
for i=2:natoms
while flag ~= 0
flag=0;
xtemp=rand*cubesize;
ytemp=rand*cubesize;
ztemp=rand*cubesize;
for j=1:i-1
xvec=xtemp-store(j,3);
yvec=ytemp-store(j,4);
zvec=ztemp-store(j,5);
xvec = xvec-cubesize* round(xvec/cubesize);
yvec = zvec-cubesize* round(yvec/cubesize);
zvec = zvec-cubesize* round(zvec/cubesize);
dist=sqrt(xvec^2+yvec^2+zvec^2);
if dist <= moldia
flag=1;
break;
end
end
end
store(i,2)=i;
store(i,3)=xtemp;
store(i,4)=ytemp;
store(i,5)=ztemp;
flag=1;
i
end
endif true
This code takes a HUGE amount more time to run. What gives? One speeds its way to i=3500 or so in a matter of seconds. The other craws to i=700 or so and then bogs. I even tried swapping out and storing everything in single vectors first with no effect.
The first code was inside a function, so I tried putting my entire new script inside a dummy function to no effect.
Thanks, Nathan

Best Answer

You should be pre-allocating the storage of the variables you are assigning in to. You might not use them all, but you can calculate a maximum possible occupancy and you can shrink the variables afterwards.