- 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.
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)
댓글 수: 0
답변 (1개)
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:
In your code snippet, "alpha" and "x0" are both scalars which is why you are observing an error with the function call.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!