フィルターのクリア

Creating a gradient ascent matlab function?

4 ビュー (過去 30 日間)
Andrew
Andrew 2014 年 12 月 6 日
コメント済み: per isakson 2014 年 12 月 6 日
I have to create a gradient ascent matlab function to find the maximum of a function. The inputs are a function handle, an initial guess, which is a 2 by 1 vector, a maximum number of iterations, and a convergence tolerance.
This is the function I'm testing it on:
function test=funcl(x0)
test=x0(1)^3-7*x0(1)^2+4*x0(1)+9*x0(2)-2*x0(2)^2;
end
It has to call a function called gs_max, which finds the maximum of a function between a lower and upper bound using the golden section method.
This is what I have so far:
function [x,fval,exitFlag]=gradient_ascent_2D(fhandle,x0,TolX,MaxIter)
for ii=1:MaxIter
if x0(1)<.000001
dx(1)=(feval(fhandle,x0(1)+x0(1)+.000001)-feval(fhandle,x0(1)))/.000001
else
dx(1)=(feval(fhandle,x0(1)+x0(1)*.000001)-feval(fhandle,x0(1)))/.000001
end
if x0(2)<.000001
dx(2)=(feval(fhandle,x0(2)+x0(2)+.000001)-feval(fhandle,x0(2)))/.000001
else
dx(2)=(feval(fhandle,x0(2)+x0(2)*.000001)-feval(fhandle,x0(2)))/.000001
end
xnew(:)=x0(:)+dx(:)
xmax=gs_max(fhandle,x0(:),xnew
When I run this, I get an error that says:
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)+9*x0(2)-2*x0(2)^2;
Error in gradient_ascent_2D (line 48)
dx(1)=(feval(fhandle,x0(1)+x0(1)*.000001)-feval(fhandle,x0(1)))/.000001
I don't understand why I'm getting this error and no matter what I try I cant get it to go away. Even if I figured this out, my function still won't be right, and I don't know where to go from here. Any ideas?

回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by