最速下下降法程序,其中梯度函数你可以用diff获得
- function y=F(x)
- y=(x(1)-15)^2+(x(2)-45)^4;
- function y=D_F(x)
- %D_F Summary of this function goes here
- % Detailed explanation goes here
- y=[0,0];
- y1=2*(x(1)-15), y2=4*((x(2)-45)^3);
- y=[y1,y2];
- format long
- x=[0,0];
- x=input('请输入初始值[x0,x1]=',[0,0]);
- s=input('请输入初始精度s=',0.1);
- g=D_F(x);
- g=g.';%转置为列向量;
- while(norm(g)>s)
- s_k=-g, r=min_F(x,s_k), x=x+r.*s_k.';
- g=D_F(x);
- g=g.';
- fprintf('The result is %8.5f\n', x);
- fprintf('The daosu is %8.5f\n', g);
- end
- axis normal;
- hold on;
- view([1,1,1]);
- for i=-100:100
- for j=-100:100
- z=[i,j], z=F(z);
- plot3(i,j,z);
- end
- end
- hold off;
复制代码 |