why do i get fminsearch undefined function error [closed]

时间秒杀一切 提交于 2019-12-24 06:29:56

问题


I'm trying to optimize a function with 2 inputs. Trying to use fminsearch but it keeps saying undefined function or variable although it is already defined.

I have already defined the function in a separate script that is in the same directory with my main script. I have a classroom license which includes optimization toolbox and there is no spelling mistake while calling the function.

function o=u(x,y)  
%some code here
end

%in a second script

init=[0.1,0.1];

b=fminsearch(o,init);

The error is:

Undefined function or variable 'o'.


回答1:


From the documentation on fminsearch, the function being minimized must have a single argument and accessed with a function handle (see this related answer).

The error you are getting is because you can't call o and use it as an input to fminsearch() since o is undefined. To get o, you have to first get u(x,y), plus as mentioned, fminsearch requires a function handle as an input.

You have several options that still use your standalone function, u(x,y).

1. Create a function handle
Define a function handle that calls u(x,y) but has a single argument which is a 2 x 1 vector, z = [x; y].

fh =@(z) u(z(1),z(2));
z0 = [1; 2];                         % Initial Guess for z = [x; y]
[z,TC] = fminsearch(fh,z0)     

2. Change the function and call it directly

The same result is possible with

[z,TC] = fminsearch(@u,z0)

if you redefine u(x,y) to be as follows:

function o=u(z) 
   x = z(1);
   y = z(2); 
   % your function code here
end


来源:https://stackoverflow.com/questions/57059519/why-do-i-get-fminsearch-undefined-function-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!