f=@(x,y,z) (1+x.^2+y.^2+z.^2)./(1+x.^2+2*y.^2+z.^4);
[X,Y,Z]=meshgrid(linspace(-pi,pi,31),linspace(-pi,pi,30),linspace(-pi,pi,39));
W=f(X,Y,Z);
slice(X,Y,Z,W,linspace(-pi,pi,3),linspace(-pi,pi,3),[])
shading interp
alpha(0.35)
axis('equal')
rotate3d on
hold on
title('Illustration av gradientmetoden','FontSize',13 ,'Interpreter','latex')
q=[1,1.5,2.5];
p=[0,0,0];
pause
while abs(f(p(1),p(2),p(3))-f(q(1),q(2),q(3)))>0.001
    p=q;
    x=p(1);y=p(2);z=p(3);
    %plot(x,y,'ro')
    h=1e-6;
    grad(1)=(f(x+h,y,z)-f(x-h,y,z))/(2*h);
    grad(2)=(f(x,y+h,z)-f(x,y-h,z))/(2*h);
    grad(3)=(f(x,y,z+h)-f(x,y,z-h))/(2*h);
    q=p+grad;
    quiver3(p(1),p(2),p(3),q(1)-p(1),q(2)-p(2),q(3)-p(3),'LineWidth',2)
    pause(0.2)
end
q=[-1,1.5,-2.5];
p=[0,0,0];
pause
while abs(f(p(1),p(2),p(3))-f(q(1),q(2),q(3)))>0.001
    p=q;
    x=p(1);y=p(2);z=p(3);
    %plot(x,y,'ro')
    h=1e-6;
    grad(1)=(f(x+h,y,z)-f(x-h,y,z))/(2*h);
    grad(2)=(f(x,y+h,z)-f(x,y-h,z))/(2*h);
    grad(3)=(f(x,y,z+h)-f(x,y,z-h))/(2*h);
    q=p+grad;
   % quiver3(p(1),p(2),p(3),q(1)-p(1),q(2)-p(2),q(3)-p(3))
    quiver3(p(1),p(2),p(3),q(1)-p(1),q(2)-p(2),q(3)-p(3),'LineWidth',2)
    pause(0.2)
end

hold off