I get the desired output from my code (gradient descent solver function) but I am unsure of how to concatenate each set of coordinates vertically into an Nx3 matrix?
I've tried to use "vertcat" but it still just prints the matrix horizontally in the command window ("Output truncated. Text exceeds maximum line length for Command Window display")
The desired output is a Nx3 matrix with each row containing the [xi,yi,zi] coordinates of the point interpolated at each stage of the algorithm.
%Function to implement the 2-Dimensional Gradient Descent method. The
%output of this function should be an [N x 3] matrix containing, on each
%row, the x, y and z co-ordinates of every position considered in the
%Gradient Descent algorithm (including start and end points)
function [xi, yi, zi] = gradient_descent2(Z,X0,Y0,xgrid,ygrid,gamma,tau)%Declare function
%[xgrid, ygrid] = meshgrid(x,y); %make mesh grid
[Gx,Gy] = gradient(Z);%compute gradient of z along entire computational
%---------------------------------2--------------------------------------%
%Use cubic interpolation to obtain starting point z(X0,Y0) and gradient at
%this point
Z0 = interp2(xgrid,ygrid,Z,X0,Y0,'cubic');gradZ0_x = interp2(xgrid,ygrid,Gx,X0,Y0,'cubic');gradZ0_y = interp2(xgrid,ygrid,Gy,X0,Y0,'cubic');%---------------------------------3--------------------------------------%
%Declare xi,yi,zi before while loop
xi = X0 - gamma*gradZ0_x; %GD algorithm:
yi = Y0 - gamma*gradZ0_y;%update = parameter - learning_rate * gradient_of_parameters
zi = interp2(xgrid,ygrid,Z,xi,yi,'cubic'); xi(1) = X0;%add starting point coordinates
yi(1) = Y0;zi(1) = Z0;j=1;%index counter
threshold = tau+1;%meet threshold condition to enter while loop
coordsOut = [];%Declare empty matrix to store coords
coordsOut(j,:) = [xi, yi, zi]; while tau <=threshold j = j+1;%update j
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'); 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
coordsOut=vertcat([coordsOut; [xi(j), yi(j), zi(j)]]);%add coordinates to matrix
threshold = sqrt((xi(j)-xi(j-1))^2 + (yi(j)-yi(j-1))^2);%threshold condition
endg=sprintf('%d ', coordsOut);%print coordinates
fprintf('Answer: %s\n', g)end
Best Answer