5/13日学习总结:最速下降法程序设计

今天完成了工程数学的实验2:最速下降法的程序设计

% 参数设置
epsilon = 1e-6;
max_iter = 10000;
x0_list = {[0;0;0;0], [1;1;1;1], [2;-0.2;0.5;0.5], [10;10;10;10]};

% 运行并记录结果
results = cell(length(x0_list), 4);
for i = 1:length(x0_list)
x0 = x0_list{i};
[x_opt, f_opt, iter, f_vals] = steepest_descent(x0, epsilon, max_iter);
results{i, 1} = x0;
results{i, 2} = iter;
results{i, 3} = f_opt;
results{i, 4} = f_vals;
end

% 显示结果
disp('初始点 | 迭代次数 | 最优函数值');
for i = 1:length(x0_list)
fprintf('%14s | %4d | %.4e\n', mat2str(x0_list{i}), results{i,2}, results{i,3});
end

% 绘制函数值变化曲线
figure;
hold on;
for i = 1:length(x0_list)
plot(log10(results{i,4}), 'DisplayName', ['初始点 ', mat2str(x0_list{i})]);
end
xlabel('迭代次数');
ylabel('log10(f(x))');
legend;
title('最优函数值随迭代次数的变化');
grid on;

%目标函数
function g = grad_f(x)
x1 = x(1); x2 = x(2); x3 = x(3); x4 = x(4);
g = zeros(4,1);
g(1) = 2(x1 + 10x2) + 40(x1 - x4)^3;
g(2) = 20
(x1 + 10x2) + 4(x2 - 2x3)^3;
g(3) = 10
(x3 - x4) - 8(x2 - 2x3)^3;
g(4) = -10(x3 - x4) - 40(x1 - x4)^3;
end
function y = f(x)
x1 = x(1); x2 = x(2); x3 = x(3); x4 = x(4);
y = (x1 + 10x2)^2 + 5(x3 - x4)^2 + (x2 - 2x3)^4 + 10(x1 - x4)^4;
end

function [x_opt, f_opt, iter, f_vals] = steepest_descent(x0, epsilon, max_iter)
x = x0;
iter = 0;
f_vals = [];
while iter < max_iter
g = grad_f(x);
norm_g = norm(g);
f_val = f(x);
f_vals = [f_vals; f_val];
if norm_g <= epsilon
break;
end
d = -g; % 负梯度方向
% 线搜索步长
phi = @(a) f(x + ad);
a = fminbnd(phi, 0, 1); % 使用[0,1]区间进行搜索
x = x + a
d;
iter = iter + 1;
end
x_opt = x;
f_opt = f(x);
end

posted @ 2025-05-13 23:50  离璨霂  阅读(14)  评论(0)    收藏  举报