使用matlab的fmincon优化,一直提示变量“x”未定义,请教问题所在?

使用matlab的fmincon函数进行优化,遇到以下问题:
%以下是建立的目标函数M文件
function f = CostObj( x ) % 目标函数
a=[1 3 5];
b=[2 4 6];
c=0*ones(1,3);
for i=1:3
c(i)=b(i)-a(i).*x(i);
end
f=sum(c);
end
%以下是在matlab主窗口中输入
x0=[2 2 2];
A=[1 2 3;2 5 9;2 7 1];
B=[11 28 19];
Aeq=[];
Beq=[];
[x fval]= fmincon(CostObj,x0,A,B,Aeq,Beq);
运行后就提示以下错误:
[x fval]= fmincon(CostObj,x0,A,B,Aeq,Beq);
??? Input argument "x" is undefined.

Error in ==> CostObj at 6
c(i)=b(i)-a(i).*log(x(i));

到底是什么原因没有搞清楚,折腾了一个下午了,郁闷,请高手指点一下,谢谢!
按照白杨龙11的方法,还是错误,如下:
[x fval]= fmincon(@(x) CostObj,x0,A,B,Aeq,Beq);
Warning: Trust-region-reflective algorithm does not solve this type of problem, using
active-set algorithm. You could also try the interior-point or sqp algorithms: set the
Algorithm option to 'interior-point' or 'sqp' and rerun. For more help, see Choosing the
Algorithm in the documentation.
> In fmincon at 472
??? Input argument "x" is undefined.
Error in ==> CostObj at 34
c(i)=b(i)-a(i).*(x(i));

第1个回答  2014-01-02
[x fval]= fmincon(@(x) CostObj(x),x0,A,B,Aeq,Beq)

追问

还是有错误呀,如下:
??? Input argument "x" is undefined.
Error in ==> CostObj at 34
c(i)=b(i)-a(i).*(x(i));
Error in ==> @(x)CostObj

追答

是[x fval]= fmincon(@(x) CostObj(x),x0,A,B,Aeq,Beq)
不是
[x fval]= fmincon(@(x) CostObj,x0,A,B,Aeq,Beq)
仔细看啊。

本回答被提问者采纳
第2个回答  2014-01-02

[x fval]= fmincon(CostObj,x0,A,B,Aeq,Beq);

改成

[x fval]= fmincon(@CostObj,x0,A,B,Aeq,Beq);

相似回答