2021-04-27 21:16

# matlab里用fmincon函数遇到问题求解答！

``````function [va,lamda] = optxestimatecon(wv,wa,g)
coder.extrinsic('myfmincon' )

x0=[1;1];
y=myfmincon(x0,wv,wa,g);
va=y(1);
lamda=y(2);
end

function y=myfmincon(x0,wv,wa,g)
f=@(x)myfuncon(x,wv,wa,g);
A = [];b = [];
Aeq = []; beq = [];
x=[0;0];
[x,fval]=fmincon(@myfuncon,x0,A,b,Aeq,beq,[0;-2*pi],[100;2*pi]);

y=x;

end

function F = myfuncon(x,wv,wa,g)

F=-(-g*(wv(3,1)-x(1)*sin(x(2)))/(x(1)*cos(x(2))+wv(1,1))+x(1)*(wa(1,1)*cos(x(2))-wa(3,1)*sin(x(2)))+wv(1,1)*wa(1,1)+wv(3,1)*wa(3,1));
end``````

F=-(-g*(wv(3,1)-x(1)*sin(x(2)))/(x(1)*cos(x(2))+wv(1,1))+x(1)*(wa(1,1)*cos(x(2))-wa(3,1)*sin(x(2)))+wv(1,1)*wa(1,1)+wv(3,1)*wa(3,1));

initVals.f = feval(funfcn{3},X,varargin{:});

[x,fval]=fmincon(@myfuncon,x0,A,b,Aeq,beq,[0;-2*pi],[100;2*pi]);

y=myfmincon(x0,wv,wa,g);

Failure in initial objective function evaluation. FMINCON cannot continue.

• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

#### 5条回答默认 最新

• Zhanghp947 2021-04-28 09:22
已采纳
``````function F = myfuncon(x,wv,wa,g)
global wv wa g;
F=-(-g*(wv(3,1)-x(1)*sin(x(2)))/(x(1)*cos(x(2))+wv(1,1))+x(1)*(wa(1,1)*cos(x(2))-wa(3,1)*sin(x(2)))+wv(1,1)*wa(1,1)+wv(3,1)*wa(3,1));
end

function y=myfmincon(wv,wa,g)
global wv wa g;
A = [];b = [];
Aeq = []; beq = [];
x0=[0;0];
[x,fval]=fmincon(@myfuncon,x0,A,b,Aeq,beq,[0;-2*pi],[100;2*pi]);
y=x;
end
end

function [va,lamda] = optxestimatecon(wv,wa,g)
global wv wa g;
coder.extrinsic('myfmincon' )
x0=[1;1];
y=myfmincon(wv,wa,g);
va=y(1);
lamda=y(2);
end
``````

把变量变成全局变量

点赞 1 评论
• hahayuy 2021-04-27 21:18

这里我输入了wv=[1;1;1] wa=[1;1;1]g=9.8

点赞 评论
• 白驹_过隙 2021-04-28 08:36

第24行你是不是括号匹配的不对，改成

``F=-(-g*(wv(3,1)-x(1)*sin(x(2)))/(x(1)*cos(x(2))+wv(1,1))+x(1)*(wa(1,1)*cos(x(2))-wa(3,1)*sin(x(2))+wv(1,1)*wa(1,1)+wv(3,1)*wa(3,1));``
点赞 评论
• 有问必答小助手 2021-04-28 11:55

您好，我是有问必答小助手，你的问题已经有小伙伴为您解答了问题，您看下是否解决了您的问题，可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案，可以点击【采纳】按钮，给回答的小伙伴一些鼓励哦～～