MATLAB: Iterations taking a long time

iterationslowwhile loop

I am trying to do particle tracking by updating the position at time t using at iterative process. Side by side, I wish to check if my y component of position is within a certain distance from defined surface's y value. If it is I want to stop the iterative process and plot only the points till now. I was running the iterative process without this 'if' statement and it took a while but gave me the right result. With the added if condition checking in the loop, my computation is taking too long (> 20 min). How do I make the code more efficient ? I need to keep the time step the same.
t = linspace(0,10,12000); % need to use 12000 time steps
xp = zeros();
yp = zeros();
yp(1) = 10*10^(-6); % setting y start point of particle (m)
x_val = linspace(-10*a,10*a,12000);
y_val = zeros(size(x_val));
y_val(1) = 10*10^(-6);
y0 = 10*10^-6;
i = 1;
d = 10*10^-6;
while i <= length(t)-1
h = t(i+1)-t(i);
xp(i+1) = xp(i) + vpa(vx(i+1),6)*h;% updating position( I haven't provided the code for computation of xp and yp as it is working fine)
yp(i+1) = yp(i) + vpa(vy(i+1),6)*h;
psi = 0;
x = x_val(i+1);
f = @(y) psi - norm(vf0)*y + m*atan2(2*a*y,x^2+y^2-a^2);
y_val(i+1) = fzero(f,y0); %obtaining the y value for the surface
y0 = y_val(i+1);
if abs(yp(i+1)-y_val(i+1))<= d/2 %checking if the difference between particle's y position value and surface y value at the same point is less than a threshold
i = length(t)-1; %attempt to end computation by making loop condition false
end
i=i+1;
end

Best Answer

Hi Sanjana,
In every iteration of the loop, you are increasing the array length by 1 (xp and yp array). This is a costly operation and your code repeats it for 12000 times! Instead, you can declare the array xp and yp to be of size 12000 before the loop execution start.
Change the lines
xp = zeros();
yp = zeros();
to
xp = zeros(12000, 1);
yp = zeros(12000, 1);
and you will be seeing a reduction in execution time.