- 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!