- clear; clc; close all; rng default;
- fun = @(x)100*(x(2)-x(1)^2)^2 + (1-x(1))^2;
- f2 = @(x) (x(1)-1/3)^2 + (x(2)-1/3)^2 - (1/3)^2;
- lb = [0,0.2];
- ub = [0.5,0.8];
- A = [];
- b = [];
- Aeq = [];
- beq = [];
- x0 = [1/4,1/4];
- nonlcon = @( x ) circlecon( x, f2 );
- x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub, nonlcon )
- function [ c, ceq ] = circlecon( x, FuncHandle )
- c = FuncHandle( x );
- ceq = [];
- end
关于fmincon函数中非线性约束函数定义的问题?
8 views (last 30 days)
Show older comments
对于x = fmincon(fun,x0,A,b,Aeq,beq,lb,ub,nonlcon)这个函数中的参数nonlcon,在给的例子里是如下的:
function [c,ceq] = circlecon(x)
c = (x(1)-1/3)^2 + (x(2)-1/3)^2 - (1/3)^2;
ceq = [];
然后引用的时候@circlecon就好了。
这里的c给了一个表达式,但是我在应用的过程中想要用求解得到的一个参数表达式
我是这样写的:
xx=fmincon(objfun,xx0,A,b,Aeq,beq,lb,ub,@noncon)
function [c,ceq] = noncon(xx)
c = [];
ceq=f2(xx(1),xx(2));
end
其中f2是之前求解得到的参数表达式通过matlabFunction转换后的形式。
会显示:
函数或变量 'f2' 无法识别。
出错 fifth>noncon (第 64 行)
ceq=f2(xx(1),xx(2));
出错 fmincon (第 654 行)
[ctmp,ceqtmp] = feval(confcn{3},X,varargin{:});
出错 fifth (第 61 行)
xx=fmincon(objfun,xx0,A,b,Aeq,beq,lb,ub,@noncon)
请问这要怎么样解决呢?谢谢了!
0 Comments
Accepted Answer
腾龙娱乐在线客服17787482287
on 17 Apr 2022
你的f2是在主代码部分定义的,而自定义函数noncon,只能调用给定的输入,即xx,或者在该函数以及主代码中都声明为全局变量的那些信息。想要调用另外一个句柄,你得在输入位置上追加,比如自定义约束函数改为
function [c,ceq] = noncon( xx, f2 ) % 其余部分略
同时主代码的 fmincon 中 @noncon 也要改为相应的 @( x ) noncon( x, f2 )
这个将函数句柄作为参数传递进自定义约束函数的写法,与示例中直接在自定义约束函数中写出约束的具体表达式,是等效的。
0 Comments
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!