梯度下降法代码matlab
时间: 2024-03-28 22:35:09 浏览: 79
梯度下降法是一种常用的优化算法,用于求解函数的最小值。下面是一个简单的梯度下降法的MATLAB代码示例:
```matlab
% 定义目标函数
function y = target_function(x)
y = x^2 + 2*x + 1;
end
% 定义目标函数的导数
function dy = derivative_function(x)
dy = 2*x + 2;
end
% 初始化参数
learning_rate = 0.1; % 学习率
max_iterations = 100; % 最大迭代次数
epsilon = 1e-6; % 收敛条件
% 初始化变量
x = 0; % 初始值
iteration = 0; % 迭代次数
% 梯度下降法迭代更新
while iteration < max_iterations
gradient = derivative_function(x); % 计算梯度
delta_x = -learning_rate * gradient; % 计算变化量
x = x + delta_x; % 更新参数
if abs(delta_x) < epsilon % 判断是否收敛
break;
end
iteration = iteration + 1;
end
% 输出结果
disp(['最小值所在的x值为:', num2str(x)]);
disp(['最小值为:', num2str(target_function(x))]);
```
这段代码实现了梯度下降法来求解一个简单的目标函数的最小值。你可以根据自己的需求修改目标函数和导数函数,并调整学习率、最大迭代次数和收敛条件等参数。
阅读全文
相关推荐













