Gradient descent with a simple function

조회 수: 4 (최근 30일)
Hai Luu
Hai Luu 2020년 3월 13일
답변: Yash 2025년 7월 20일
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