How do you properly write a function to use fmincon from optimization tool?
14 次查看(过去 30 天)
显示 更早的评论
I have been asked to use 'optimtool' to minimize a non linear problem. I was told to write a constraints script and an objective script. I also previously heard that the function called out in the script is supposed to be the same as the name of the script. But sometimes I get errors when I do that saying that the function has a duplicate name. My main issues are as follows:
1. Optimtool, my objective function, and my constraints function keeps giving the error "Not Enough Input Arguments" 2. My constraints function will not recognize my constraint lines. It just says "Error in Constraints7_8 (line 7) g(1)=axial-150000000;" Below I'm showing what I have for each script.
%Objective7_8
function [f] = Objective7_8(D,H)
% f returns value of objective function
% Evaluate objective function
f = 6.60*D.^2*(H.^2+4800).^0.5;
end
%Constraints7_8
function [g,h] = Constraints7_8(axial,P,Pcr,H,D)
% g returns inequality constraints
% h returns equality constraints
% Inequality constraints
g(1) =axial-150000000;
g(2) =P-(Pcr/2);
g(3) =50-H;
g(4) =H-500;
g(5) =0.5-D;
g(6) =D-50;
% Equality constraints
h = [];
end
%Problem7_8
D=0.5:0.11:50;
H=50:1:500;
%Constants%
W=60000;
B=120;
sigma_a=150000000;
E=7500000;
rho=2.8;
FS=2;
%Parameters%
I=(pi/64)*D.^4;
l=(H.^2 +(1/3)*B^2).^0.5;
Pcr=(pi^2*E*I)/I.^2;
P=(W*l/3.*H);
axial=P/D;
7 个评论
回答(1 个)
Alan Weiss
2018-9-21
Take a look at the Getting Started example. Your main problem is that you have too many variables; all your variables need to be put into one, typically called x. See also Writing Scalar Objective Functions for instructions on how to do this.
Alan Weiss
MATLAB mathematical toolbox documentation
3 个评论
Stephen23
2018-9-21
编辑:Stephen23
2018-9-21
"So how would I do the same with my variables?"
Just like Alan Weiss wrote: put all of your variables into one array, e.g.: if you have three scalar input arguments, then your array will have three elements. Don't think of your "variables" as being separate input arguments, think of them as being elements of one array. Use indexing to access them.
"I'm wondering why I get the not enough inputs error if there are too many variables?"
fmincon calls the function handle with one input argument (i.e. x, an array). MATLAB gives that error message because you wrote your function to require multiple input arguments, so when it is only provided with one input argument then it complains that it is not getting all of the input arguments that it expects!
If it makes you any happier, you could do something like this:
fun = @(x) Constraints7_8(x(1),x(2),x(3),x(4),x(5));
and use fun in fmincon. Adjust the indices to suit the sizes of the input arguments.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Get Started with Optimization Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!