"Index exceeds the number of array elements (1)." error
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
I am trying to write two line search functions to help me write code later for implementing different ways to minimize functions using step size. This is what I have so far and I'm not sure why I'm getting this error. I get the same error for both of the algorithms that is
"Index exceeds the number of array elements (1).
Error in sym/subsref (line 900)
R_tilde = builtin('subsref',L_tilde,Idx);
Error in linesearch2 (line 4)
grad = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1)); 200*(x(2)-x(1)^2)];"
function [alpha] = linesearch2(nsteps)
syms x
f = @(x)100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
grad = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1)); 200*(x(2)-x(1)^2)];
alpha(0) = 0;
alpha(1) = 1;
c1 = 10^-4;
c2 = 0.9;
for i = 1:nsteps
if (f(alpha(i)) > f(0)+c1*alpha(i)*grad(0)||(f(alpha(i)) > f(alpha(i-1))))
alpha = lszoom(alpha(i-1), alpha(i));
return;
end
if abs(grad(alpha(i))) <= abs(c2*grad(0))
alpha = alpha(i);
return;
end
if grad(alpha(i)) >= 0
alpha = lszoom(alpha(i), alpha(i-1));
return;
end
alpha(i+1) = 2*alpha;
end
Error('step size alpha not found within 10 iterations')
end
And the lszoom function I'm trying to call is
function [alpha] = lszoom(alphalo, alphahigh)
syms x
f = @(x)100*(x(2) - x(1)^2)^2 + (1 - x(1))^2;
grad = [-400*(x(2)-x(1)^2)*x(1)-2*(1-x(1)); 200*(x(2)-x(1)^2)];
alpha(0) = 0;
alpha(1) = 1;
c1 = 10^-4;
c2 = 0.9;
nsteps = 50;
for i = 1:nsteps
alpham = (alphalo + alphahigh) / 2;
if (f(alpham) > alpha(0)+c1*alpham*grad(0)||f(alpham)>f(alphalo))
alphahigh = alpham;
else
if abs(grad(alpham)) <= c2*abs(grad(0))
alpha = alpham;
return;
end
if grad(alpham)*(alphahigh-alphalo) >= 0
alphahigh = alphalo;
end
alphalo = alpham;
end
end
Error('step length alpha not found within 50 iterations')
end
I'm not great at MATLAB so any help/advice would be really wonderful!
0 Kommentare
Antworten (1)
Walter Roberson
am 20 Feb. 2020
You made f an anonymous function but your grad is a symbolic expression not an anonymous function. You are invoking grad later as if you expect it to be a function.
6 Kommentare
Walter Roberson
am 21 Feb. 2020
Read the remarks at the beginning of the second image again: f(x) is described as a function of one variable. Your f and your grad are functions of three variables, and the algorithm does not apply (not unless you are willing to freeze two out of the three variables for the duration of the search.)
The second image talks explicitly about one-dimensional minimization; doing a three-dimension minimization instead violates the warrantee.
Siehe auch
Kategorien
Mehr zu Linear Algebra finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!