function [k, x, val] = dampnm(fun, gfun, Hess, x0, epsilon)
% 输入:% fun - 被优化的函数;% gfun - 目标函数的梯度;% Hess - 目标函数的Hessian矩阵;% x0 - 初始点;% epsilon - 收敛阈值;% 输出:% k - 迭代次数;% x - 极值点;% val - 极值点的函数值;
k = 1; % 初始化迭代计数器
gk = feval(gfun, x0); % 计算初始梯度和Hessian矩阵
Gk = feval(Hess, x0);
while norm(gk) > epsilon
dk = -Gk\gk; % 求解线性方程组以找到搜索方向
x0 = x0 + dk; % 更新点
gk = feval(gfun, x0); % 计算新点的梯度和Hessian矩阵
Gk = feval(Hess, x0);
k = k + 1; % 迭代计数器递增
if k > 10000 % 如果迭代次数太多,退出循环
warning('The method did not converge after 10000 iterations.');
break;
end
end
x = x0; % 输出最终迭代结果
val = feval(fun, x0);
end
脚本:
% 使用符号变量定义目标函数、梯度和Hessian矩阵
syms x1 x2 x3 x4;
funf_sym = (x1 + 10*x2)^2 + 5*(x3 - x4)^2 + (x2 - 2*x3)^4 + 10*(x1 - x4)^4;
gradf_sym = gradient(funf_sym, [x1, x2, x3, x4]);
hessf_sym = hessian(funf_sym, [x1, x2, x3, x4]);
% 将符号表达式转换为函数句柄,明确设置为接受列向量
funf = matlabFunction(funf_sym, 'Vars', {[x1; x2; x3; x4]});
gradf = matlabFunction(gradf_sym, 'Vars', {[x1; x2; x3; x4]});
hessf = matlabFunction(hessf_sym, 'Vars', {[x1; x2; x3; x4]});
% 初始化初始点和精度
x0 = [2; 2; 2; 2]; % 初始点
epsilon = 1e-6; % 收敛阈值
% 调用牛顿法
[k, x_opt, f_opt] = dampnm(funf, gradf, hessf, x0, epsilon);
% 输出结果
fprintf('迭代次数: %d\n极值点 x: [%f, %f, %f, %f]\n极值点的函数值: %f\n', ...
k, x_opt(1), x_opt(2), x_opt(3), x_opt(4), f_opt);
标签:工程,sym,实验,x3,x2,数学,x0,x1,x4 From: https://www.cnblogs.com/yuanxinglan/p/18219799