简体   繁体   中英

Using fmincon in Matlab with script function

I am solving the following fmincon problem in Matlab

clear
rng default
XZW_temp=[0.5450    0.8175   -0.5451    0.2724];
X1_temp=[0    0.0852         0   -0.0852];
X2_temp=[2.0132    1.0066   -2.0132   -1.0066];
options = optimset('linprog');
options.Display = 'off';


fun=@(x)inner_max(x,XZW_temp, X1_temp, X2_temp, options);
ub=Inf*ones(4,1);
lb=zeros(4,1);
x0=ones(4,1);
[~, f]=fmincon(fun,x0,[],[],[],[],lb,ub); 

where inner_max is the following

function i_m=inner_max(x,XZW_temp, X1_temp, X2_temp, options)

f=-[x'*XZW_temp.'; x'*X1_temp.'; x'*X2_temp.'];

Aeq=[1 0 0];

beq=1; 

lb=-Inf*ones(3,1);
ub=Inf*ones(3,1);

[~,fval] = linprog(f,[],[],Aeq,beq,lb,ub,options);

i_m=-fval; 

end

I get the following error

In an assignment  A(:) = B, the number of elements in A and B must be the same.

Error in finitedifferences

Error in computeFinDiffGradAndJac

Error in barrier

Error in fmincon (line 798)
    [X,FVAL,EXITFLAG,OUTPUT,LAMBDA,GRAD,HESSIAN] = barrier(funfcn,X,A,B,Aeq,Beq,l,u,confcn,options.HessFcn, ...

I do not understand what I'm doing wrong. Could you help?

I think you can write your anonymous function in fmincon like below, such that arguments XZW_temp , X1_temp ,and X2_temp can be pass to fmincon from global environment, ie,

[~, f]=fmincon(@(x) inner_max(x,XZW_temp, X1_temp, X2_temp),x0,[],[],[],[],lb,ub);

such that

>> f
f =  1.0898

NB: I removed option from inner_max , so the function looks like

function i_m=inner_max(x,XZW_temp, X1_temp, X2_temp)

f=-[x'*XZW_temp.'; x'*X1_temp.'; x'*X2_temp.'];

Aeq=[1 0 0];

beq=1; 

lb=-Inf*ones(3,1);
ub=Inf*ones(3,1);

[~,fval] = linprog(f,[],[],Aeq,beq,lb,ub);

i_m=-fval; 

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM