"Index exceeds the number of array elements (1)." error

조회 수: 11(최근 30일)
Sarah Johnson 2020년 2월 20일
댓글: Walter Roberson 2020년 2월 21일
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)
function [alpha] = linesearch2(nsteps)
syms x
f = @(x)100*(x(2) - x(1)^2)^2 + (1 - 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
alpha = alpha(i);
return;
end
alpha = lszoom(alpha(i), alpha(i-1));
return;
end
alpha(i+1) = 2*alpha;
end
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;
alpha(0) = 0;
alpha(1) = 1;
c1 = 10^-4;
c2 = 0.9;
nsteps = 50;
for i = 1:nsteps
alpham = (alphalo + alphahigh) / 2;
alphahigh = alpham;
else
alpha = alpham;
return;
end
alphahigh = alphalo;
end
alphalo = alpham;
end
end
end
I'm not great at MATLAB so any help/advice would be really wonderful!

댓글을 달려면 로그인하십시오.

답변(1개)

Walter Roberson 2020년 2월 20일
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표시숨기기 이전 댓글 수: 5
Walter Roberson 2020년 2월 21일
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.

댓글을 달려면 로그인하십시오.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!