Error: Array indices must be positive integers or logical values. implementing fletcher reeves method
1 view (last 30 days)
Show older comments
I am trying to implement the fletcher reeves method in matlab using "fminbnd". This is my code:
function[xmin,valormin] = fletcherreeves2(x0,funcao,grad,tol)
d0=-grad(x0);
x=x0;
d=d0;
k=0;
while norm(grad(x))>tol
f_lambda=@(lambda) funcao(x+lambda*x);
alpha=fminbnd(f_lambda,0,1000);
xk=x+alpha*d;
gradnovo=grad(xk);
beta=(norm(gradnovo))^2/(norm(grad(x)))^2;
dk=-gradnovo+beta*d;
k=k+1;
x=xk;
d=dk;
grad=gradnovo;
end
xmin=x;
valormin=funcao(xmin);
end
I am getting this error:
Error in fletcherreeves2 (line 6)
while norm(grad(x))>tol
I have tried using the following debug statements:
disp(d0)
disp(grad(x0))
disp(norm(grad(x0)))
disp(norm(grad(x0))>tol)
I am using the following input:
fletcherreeves2([5;5],@(x) x(1)^2-x(1)*x(2)+4*x(2)^2+3*x(1)+2,@(x) [2*x(1)-x(2)+3,-x(1)+8*x(2)],10^-(6))
and always receive the output i am supposed to, so I really don't know what my error is and I really have no idea what to do, any help is greatly appreciated!
0 Comments
Answers (2)
Walter Roberson
on 19 Mar 2023
fletcherreeves2([5;5],@(x) x(1)^2-x(1)*x(2)+4*x(2)^2+3*x(1)+2,@(x) [2*x(1)-x(2)+3,-x(1)+8*x(2)],10^-(6))
The third parameter there is an anonymous function
function[xmin,valormin] = fletcherreeves2(x0,funcao,grad,tol)
The anonymous function is being received under the name grad
d0=-grad(x0);
The anonymous function gets invoked.
while norm(grad(x))>tol
First time through, the anonymous function gets invoked.
gradnovo=grad(xk);
There too, returning a numeric value.
grad=gradnovo;
The numeric value is assigned to the variable grad
while norm(grad(x))>tol
Second time through, grad is a numeric variable that you are indexing at locations given by x
0 Comments
Torsten
on 19 Mar 2023
Edited: Torsten
on 20 Mar 2023
[xmin,valormin]=fletcherreeves2([5;5],@(x) x(1)^2-x(1)*x(2)+4*x(2)^2+3*x(1)+2,@(x) [2*x(1)-x(2)+3;-x(1)+8*x(2)],10^-(6))
function[xmin,valormin] = fletcherreeves2(x0,funcao,grad,tol)
gradvelho = grad(x0);
d0=-gradvelho;
x=x0;
d=d0;
k=0;
while norm(gradvelho)>tol
f_lambda=@(lambda) funcao(x+lambda*d);
alpha=fminbnd(f_lambda,0,1000);
xk=x+alpha*d;
gradnovo=grad(xk);
beta=(norm(gradnovo))^2/(norm(gradvelho))^2;
dk=-gradnovo+beta*d;
k=k+1;
x=xk;
d=dk;
gradvelho=gradnovo;
end
xmin=x;
valormin=funcao(xmin);
end
0 Comments
See Also
Categories
Find more on Instrument Connection and Communication in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!