问题描述
我想用fmincon解决一个简单的问题,但是它返回一条错误消息.我有2个函数f_2和f_1,我想分别最小化它们.我想在一个matlab函数(即我的fun.m)中编写f_1和f_2.然后,我想使用主代码中的索引来调用它们中的每一个.这是您可以看到的代码:
I want to solve a simple problem with fmincon but It returns an error message.I have 2 functions f_2 and f_1 and I want to minimize each of them individually. I want to write f_1 and f_2 in a one matlab function i.e., my fun.m. Then I want to call each of them using an index from the main code. Here is the code you can see:
main code:
AA=[1 2 -1 -0.5 1];bb=-2;
xo=[1 1 1 1 1];
VLB=[-1 -1 -1 -1 -1];
VUB=[100 100 100 100 100];
for F_index = 1:2
[x,fval]=fmincon(@myfun,xo,AA,bb,[],[],VLB,VUB)
end
%%这是函数
function f = myfun(x, F_index)
if F_index == 1
f = norm(x)^2 - 4*x(4)*(x(2) + 3.4*x(5))^2 ;
end
if F_index == 2
f = 100*(x(3) - x(5)) + (3*x(1)+2*x(2) - x(3)/3)^2 + 0.01*(x(4) - x(5))
end
未定义的函数或变量'F_index'.
Undefined function or variable 'F_index'.
fmincon中的错误(第564行) initVals.f = feval(funfcn {3},X,varargin {:});
Error in fmincon (line 564) initVals.f = feval(funfcn{3},X,varargin{:});
主要错误(第6行) [x,fval] = fmincon(@ myfun,xo,AA,bb,[],[],VLB,VUB) 造成原因: 最初用户提供的目标失败 功能评估. FMINCON无法继续.
Error in main (line 6) [x,fval]=fmincon(@myfun,xo,AA,bb,[],[],VLB,VUB) Caused by: Failure in initial user-supplied objective function evaluation. FMINCON cannot continue.
推荐答案
错误消息明确指出了问题所在:函数myfun
中未定义变量F_index
. Matlab中的变量的作用域仅限于定义变量的功能(或工作区").可以将它们设置为全局",但这不是您通常要执行的操作.
The error message clearly states the problem: The variable F_index
is undefined within the function myfun
. Variables in Matlab have a scope restricted to the function (or rather "workspace") within which they are defined. They can be made "global", but that's not something you normally want to do.
一种解决方法是使用嵌套函数,其中嵌套函数的变量在嵌套函数中可用:
A workaround is to use nested functions, where variables of the enclosing function become available in the nested function:
function main_function
AA=[1 2 -1 -0.5 1];bb=-2;
xo=[1 1 1 1 1];
VLB=[-1 -1 -1 -1 -1];
VUB=[100 100 100 100 100];
F_index = 1;
for F_index = 1:2
[x,fval]=fmincon(@myfun,xo,AA,bb,[],[],VLB,VUB)
end
function f = myfun(x)
if F_index == 1
f = norm(x)^2 - 4*x(4)*(x(2) + 3.4*x(5))^2 ;
end
if F_index == 2
f = 100*(x(3) - x(5)) + (3*x(1)+2*x(2) - x(3)/3)^2 + 0.01*(x(4) - x(5))
end
end
end
现在myfun
嵌套在main_function
中,并可以访问其变量.
Now myfun
is nested in main_function
and has access to its variables.
这篇关于使用fmincon matlab时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!