问题描述
我正在尝试使用2个输入优化函数.尝试使用fminsearch,但是尽管已经定义了fminsearch,但它总是说未定义的函数或变量.
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);
错误是:
推荐答案
摘录自 fminsearch
,要最小化的函数必须具有单个参数,并使用功能句柄(请参阅与此相关的 answer ).
From the documentation on fminsearch
, the function being minimized must have a single argument and accessed with a function handle (see this related answer).
您遇到的错误是因为您无法调用o
并将其用作fminsearch()
的输入,因为o
是未定义的.要获取o
,您必须首先获取u(x,y)
,此外,如前所述,fminsearch
需要函数句柄作为输入.
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.
您有几个选项仍使用独立功能,u(x,y)
.
1.创建功能句柄
定义一个调用u(x,y)
但具有单个参数的函数句柄,该参数是2 x 1向量z = [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.更改功能并直接调用
使用
[z,TC] = fminsearch(@u,z0)
如果将u(x,y)
重新定义为以下内容:
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
这篇关于为什么我得到fminsearch未定义函数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!