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
%% here is the function
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
Undefined function or variable 'F_index'.
Error in myfun (line 2) if F_index == 1
Error in fmincon (line 564) initVals.f = feval(funfcn{3},X,varargin{:});
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.
myfun1
,myfun2
etc. But the solution outlined in my updated answer should also work. Note that its better to use aswitch
statement instead of a series ofif
s. – A. Donda