MATLAB: “Index exceeds matrix dimensions” while loop condition

gradient descentindexingMATLABmatrixwhile loop

I am writing a function which implements the gradient descent algorithm.
I wish to run a while loop until the following threshold condition is met:
which adds coordinates found by the algorithm into an Nx3 matrix at each interation.
I also wish to add a starting point (coordinates which are input to the function, therefore not calculated within the loop) to this matrix.
This is my current attempt – please could you help or direct me to the relevant guides for what I want? I'm sure there are many more elegant ways to write it, but I think what I'm mostly confused about is the indexing ("index exceeds matrix dimensions") in the while loop condition.
coordsOut(j,:) = [xi, yi, zi];
xi(1) = X0;
yi(1) = Y0;
zi(1) = Z0;%add starting point
xi(2) = xi(1) - gamma*gradZi_x; %update x,y coords

yi(2) = yi(1) - gamma*gradZi_y; %%update = learning_rate * gradient_of_parameters

zi(2) = interp2(xgrid,ygrid,Z,xi(1),yi(1),'cubic');%update z with cubic interpolation from new x,y coords

gradZi_x = interp2(xgrid,ygrid,Gx,xi(1),yi(1),'cubic');%update px,py gradients

gradZi_y = interp2(xgrid,ygrid,Gy,(1),yi(1),'cubic');
if tau >sqrt((xi(2)-xi(1)^2) + (yi(2)-yi(1))^2)
g=sprintf('%d ', coordsOut);
fprintf('Answer: %s\n', g)
else
j = 2;
while tau <=sqrt((xi(j)-xi(j-1)^2) + (yi(j)-yi(j-1))^2)%threshold condition
xi(j) = xi(j-1) - gamma*gradZi_x; %update x,y coords
yi(j) = yi(j-1) - gamma*gradZi_y; %%update = learning_rate * gradient_of_parameters
zi(j) = interp2(xgrid,ygrid,Z,xi(j-1),yi(j-1),'cubic');%update z with cubic interpolation from new x,y coords
gradZi_x = interp2(xgrid,ygrid,Gx,xi(j-1),yi(j-1),'cubic');%update px,py gradients
gradZi_y = interp2(xgrid,ygrid,Gy,xi(j-1),yi(j-1),'cubic');
j = j+1;
end
g=sprintf('%d ', coordsOut);
fprintf('Answer: %s\n', g)
end

Best Answer

Try checking the length in your while loop
while tau <=sqrt((xi(j)-xi(j-1)^2) + (yi(j)-yi(j-1))^2) && j <= length(xi) %threshold condition
If you want a warning when this happens, then add this just before the end of the while loop
j = j + 1; %( Existing code)
if j > length(xi)
warningMessage = sprintf('j (%d) is longer than length of xi (%d), so exiting loop.', j, length(xi))
uiwait(warndlg(warningMessage);
break;
end