Gradient descent with a simple function

4 views (last 30 days)
Hai Luu
Hai Luu on 13 Mar 2020
Answered: Yash on 20 Jul 2025
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)

Answers (1)

Yash
Yash on 20 Jul 2025
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.

Community Treasure Hunt

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

Start Hunting!