次梯度法matlab代码
时间: 2023-11-05 15:29:35 浏览: 36
以下是一个使用次梯度法求解无约束最小化问题的 MATLAB 代码示例:
function [x, fval] = subgradient_method(fun, x0, max_iter, step_size, tol)
% Subgradient Method for Unconstrained Optimization
% fun: objective function to minimize
% x0: initial guess
% max_iter: maximum number of iterations
% step_size: step size (learning rate)
% tol: tolerance for stopping criterion
% initialization
x = x0;
fval = fun(x);
iter = 0;
converged = false;
while ~converged && iter < max_iter
% calculate subgradient
g = subgrad(fun, x);
% update x
x = x - step_size * g;
% update function value
fval_new = fun(x);
% check convergence
if abs(fval_new - fval) < tol
converged = true;
end
% update iteration and function value
iter = iter + 1;
fval = fval_new;
end
function g = subgrad(fun, x)
% calculate subgradient of objective function at x
% using forward difference approximation
h = 1e-6;
g = zeros(size(x));
for i = 1:length(x)
x_plus = x;
x_plus(i) = x_plus(i) + h;
g(i) = (fun(x_plus) - fun(x)) / h;
end
注意:此代码仅供参考,具体实现可能因问题而异。