matlab实现牛顿迭代法求解二元函数最优点并绘制动态图像
程序员文章站
2024-01-15 19:01:40
...
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. 迭代求解并绘制图像
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