MATLAB: “fmincon” optimization with nonlinear constraints: colon error

arraycolon errorfminconfunctionnested functionoptimization

Hello!
This is my second post for the same topic (solar production with an hourly resolution over 15 years), but I have a different question this time. Thanks in advance for the help! Here's the issue:
I have an objective function that I can solve with fmincon (I think), only one nonlinear equality constraint and variable bounds. My variable is Cpv and it will be a single number, not an array.
Function = @ObjFun3; %Saved in the same directory with filename=function name

nonlinconst = @PVnonlincon; %Saved in the same directory with filename=function name
[Cpv,fval] = fmincon(Function,10000,[],[],[],[],0,10000,nonlinconst);
If I eliminate the nonlincon arguement, fmincon finds a solution (which is obviously not sufficient, I just wanted to check where the problem is). The error I am getting is:
Input arguments to function include colon operator. To input the colon
character, use ':' instead.
Error in fmincon (line 651)
initVals.nceq = ceqtmp(:);
Error in Opt3 (line 29)
[Cpv,fval] = fmincon(Function,10000,[],[],[],[],0,10000,nonlinconst);
Do I have a conceptual error somewhere, or a command that I cannot use when declaring a function, or an argument that fmincon doesn't accept?
ObjFun3 is defined as:
function [OF] = ObjFun3(Cpv)
DataW = struct2array(load('DataNinjaW+PV.mat','DataW')); %8760x15x6 array



DataPV = struct2array(load('DataNinjaW+PV.mat','DataPV')); %8760x15x6 array
Cn = 10000;
r = size(DataW,1);
Pw = DataW(r,1,1);
N = Cn .* ones(size(Pw));
NinjaPV = DataPV(r,1,Loc);
function F = Fed_pv(Cpv)
F = min((NinjaPV.*Cpv/1000), (N-Pw));
end
OF = sum(N - Pw - Fed_pv(Cpv), 'all');
end
And PVnonlincon is defined as:
function [c_ineq,c_eq] = PVnonlincon(Cpv)
DataW = struct2array(load('DataNinjaW+PV.mat','DataW')); %8760x15x6 array
DataPV = struct2array(load('DataNinjaW+PV.mat','DataPV')); %8760x15x6 array
Cn = 10000;
r = size(DataW,1);
Pw = DataW(r,1,1);
N = Cn .* ones(size(Pw));
NinjaPV = DataPV(r,1,Loc);
c_ineq = [ ];
Anonymous = @(Cpv) Fed_Pv(Cpv) + NotFed(Cpv) - NinjaPV*(Cpv);
c_eq = Anonymous;
function NF = NotFed(Cpv)
NF = max(0,(NinjaPV*Cpv/1000)+Pw-N);
end
function F = Fed_Pv(Cpv)
F = min((NinjaPV*Cpv/1000), (N-Pw));
end
end

Best Answer

You are returning a function handle in c_eq, when really you should be evaluating the function at Cpv,
c_eq = Anonymous(Cpv);
Aside from that, however, both your objective and constraints are non-differentiable functions, and so are outside the scope of what fmincon can handle. You should probably use ga() instead.