필터 지우기
필터 지우기

Why is this variable undefined?

조회 수: 2 (최근 30일)
Andrew
Andrew 2014년 12월 7일
댓글: Image Analyst 2014년 12월 7일
I have a function that uses gradient ascent to calculate a maximum, but I keep getting an error. fhandle is a function handle, x0 is a length 2 vector with initial guesses, tolx is the tolerance, and maxiter is the maximum iterations. This is the part of the function that gives me an error:
function [x,fval,exitFlag]=gradient_ascent_2D(fhandle,x0,TolX,MaxIter)
x1=x0(1);
x2=x0(2);
iter=0;
a=length(x0);
for i=1:MaxIter
iter=iter+1
*** dx1=(feval(fhandle,x1+.001*x1)-feval(fhandle,x1))/.001
dx2=(feval(fhandle,x2+.001*x2)-feval(fhandle,x2))/.001
dx=[dx1 dx2]
if norm(dx)<Tolx
x(1)=x1+dx1*.001
x(2)=x2+dx2*.001
break
end
The stars mark the line the error occurs on. This is what the error reads:
Attempted to access x0(2); index out of bounds because numel(x0)=1.
Error in funcl (line 2)
test=x0(1)^3-7*x0(1)^2+4*x0(1)*x0(2)-2*x0(2)^2;
Error in gradient_ascent_2D (line 85)
dx1=(feval(fhandle,b)-feval(fhandle,x1))/.001
For some reason x0(2) isn't defined because the length of x0 is 1, but I am inputting it as a length 2 vector. Any ideas what the problem is, or an easier way to do this?
  댓글 수: 4
Andrew
Andrew 2014년 12월 7일
편집: Image Analyst 2014년 12월 7일
I took out the feval part, now it can calculate dx1 and dx2, but it runs into the same problem later in the function. It happens on these lines:
if dx(1)<0
xnew(1)=x0(1)-dx(1)*.001
** x0(1)=gs_max(fhandle,x0(1),xnew(1))
with the same error, x0 is not length 2. gs_max is another function I call to find the maximum using golden section between 2 bounds.

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

답변 (2개)

Image Analyst
Image Analyst 2014년 12월 7일
Put these as the first lines in your gradient_ascent_2D function
whos x0
x0 % Don't use a semi colon
What do you see in the command window?
  댓글 수: 1
Andrew
Andrew 2014년 12월 7일
>> gradient_ascent_2D(@funcl,[.29 .23],.001,1000) Name Size Bytes Class Attributes
x0 1x2 16 double
x0 =
0.2900 0.2300
and then the same error as before.

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


Guillaume
Guillaume 2014년 12월 7일
You define xo as a vector of length 2 in gradient_ascend_2D, but the problem is in funcl, where you must have defined a different x0, this one of length 1.
If you want to use the xo of gradient_ascend_2D in funcl, you'll have to pass it as an argument.
  댓글 수: 1
Guillaume
Guillaume 2014년 12월 7일
Having now seen the code for funcl, I'll say use more descriptive variable names than x0, x1, x2, etc,
The problem is that the x0 local to funcl is not the same x0 local to gradient_ascend_2D. When you calculate dx1, the x0 local to funcl is just x1 from gradient_... while for dx2 it's just x2.
There seems to be some confusion on the purpose of all these xk variables.

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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by