Gradient descent with a simple function

4 次查看(过去 30 天)
Hi everyone, I am currently practicing this method on a simple function, however I keep getting this error and I do not know how to fix it.
Here is my programe:
fplot(@(x)myfun(x),[-10,10]);
alpha = 0.01;
x0 = -5;
% -------using GD----------------------
[x grad] = gradient(alpha,x0)
% hold on
% figure;
fprintf('x = %f\n',x);
fprintf('grad = %f\n',grad);
% ------------------------------
function f = myfun(x)
f = x^2+5*sin(x);
end
function [x,grad] = gradient(alpha,x0)
grad = 2*x0+5*cos(x0);
x = x0;
for i = 0:50
x = x - alpha*grad;
if abs(grad(x))< 0.01
break
display(x);
% grad = grad(x);
end
end
Here is the error that I got
Array indices must be positive integers or logical values.
Error in gradient (line 6)
if abs(grad(x))< 0.01
Error in Gradient_descent_1 (line 5)
[x grad] = gradient(alpha,x0)

回答(1 个)

Yash
Yash 2025-7-20
The function gradient(F) computes and returns the one-dimensional numerical gradient of vector "F". The function takes the input arguments:
  • F - Input array, specified as a vector, matrix, or multidimensional array.
  • h (optional) - Uniform spacing between points in all directions.
  • hx, hy, hN (optional) - Spacing between points in each direction, specified as separate inputs of scalars or vectors. The number of inputs must match the number of array dimensions of F.
In your code snippet, "alpha" and "x0" are both scalars which is why you are observing an error with the function call.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by