matlab实现牛顿迭代法求解二元函数最优点并绘制动态图像

matlab实现牛顿迭代法求解二元函数最优点并绘制动态图像1.定义目标函数,及其雅可比矩阵和海塞矩阵:function[f_val,f_grad_val,f_hess_val]=V_func(x_val,y_val)symsxy;f=(x-2)^4+((x-2)^2)*(y^2)+(y+1)^2;f_grad=jacobian(f,[x;y]);f_hess=jacobian(f_grad,[x,y]);f_val=subs(f,{x,

1. 定义目标函数,及其雅可比矩阵和海塞矩阵:

function [f_val, f_grad_val, f_hess_val] = V_func(x_val, y_val)
    syms x y;
    
    f = (x-2)^4+((x-2)^2)*(y^2)+(y+1)^2;
    
    f_grad = jacobian(f, [x; y]);
    f_hess = jacobian(f_grad, [x, y]);
    
    f_val = subs(f, {x, y}, {x_val, y_val});
    f_grad_val = subs(f_grad, {x, y}, {x_val, y_val});
    f_hess_val = subs(f_hess, {x, y}, {x_val, y_val});
end
只听到从架构师办公室传来架构君的声音:
移得绿杨栽后院。有谁来对上联或下联?

2. 迭代求解并绘制图像

此代码由Java架构师必看网-架构君整理
clear clc init_point = [12, 15]'; iter_max = 30; [f_init, f_grad_init, f_hess_init] = V_func(init_point(1), init_point(2)); % 由于是每次迭代需要更新两个变量,因此需要2*x大小的数组存储 x_steps_val = zeros(2, iter_max); f_steps_val = zeros(1, iter_max); x_steps_val(:, 1) = init_point; f_steps_val(:, 1) = f_init; err_val = inf; err_max = 1e-6; iter = 1; residual = zeros(1, iter_max); while err_val > err_max if iter == iter_max disp('已经达到最大迭代次数'); break; end x = x_steps_val(:, iter); [f_val_prev, f_grad_val, f_hess_val] = V_func(x(1), x(2)); x_steps_val(:, iter + 1) = x_steps_val(:, iter) - inv(f_hess_val)*(f_grad_val'); x_2 = x_steps_val(:, iter + 1); [f_val_cur, f_grad_val, f_hess_val] = V_func(x_2(1), x_2(2)); residual(:, iter) = norm(f_val_prev - f_val_cur); err_val = residual(:, iter); if err_val < err_max disp('找到满足精度要求的解'); disp(x_2); disp(['迭代次数为',num2str(iter)]); break; end iter = iter + 1; end % 定义三维图像显示范围 x = -15:0.5:15; y = -15:0.5:15; % 绘制三维函数图像 [xx, yy] = meshgrid(x, y); [f, f_grad, f_hess] = V_func(xx, yy); figure; mesh(xx, yy, double(f)); alpha(0.3) hold on; % 绘制迭代点图像 for i = 1 : iter span = 1 : 1 : i-1; scatter3(x_steps_val(1,i), x_steps_val(2,i), f_steps_val(i), 'MarkerEdgeColor','k','MarkerFaceColor',[0 .75 .75]) plot3(x_steps_val(1,span), x_steps_val(2,span), f_steps_val(span), 'r-', 'LineWidth', 3) pause(1); M(i) = getframe; end

 

架构君码字不易,如需转载,请注明出处:https://javajgs.com/archives/166218
0
 

发表评论