variable number of inputs in a function
이전 댓글 표시
I am using ML estimation. If I have initial values par0, data in a matrix mData and if I need to find 2 parameters par(1) and par(2) that maximise the likelihood function, it looks like this:
fLL = @(par) - fLogLik(par(1),par(2),mData);
[par, fval, eflag] = fmincon(fLL,par0,[],[],[],[],[iLb iLb],... % Calls the optimisation function
[iUb iUb],[],options);
where the iLB and iUb are used defined lower and upper bounds.
Now, this works fine. My issue is that I want to make this completely general. Sometimes I need 2 parameters, other times I need, say, 4. When 4 are needed, I'd have:
fLL = @(par) - fLogLik(par(1),par(2),par(3),par(4),mData);
[par, fval, eflag] = fmincon(fLL,par0,[],[],[],[],[iLb iLb iLb iLb],... % Calls the optimisation function
[iUb iUb iUb iUb],[],options);
How can I implement this in an efficient way (assuming that I have a variable before this, say iS, with the number of parameters)? Also, the same problem happens again insided the fLogLik function, which uses a matrix mQ as an input. This matrix is defined as :
mQ = diag(par1,par2,par3,...)
The bit
[iLb iLb iLb iLb]
is easy to handle by defining
iLb * ones(1,iS).
I am just not sure about how to specify the number of parameters in fLogLik as a function of iS.
채택된 답변
추가 답변 (1개)
You should not write fLogLik with separate input arguments for par(1), par(2),..par(N). You should write fLogLik to accept the complete vector par as input
fLL = @(par) - fLogLik(par,mData);
You can use generic operations inside fLogLik to deal with the unknown length of par. Wherever you can, you should also be vectorizing operations inside fLogLik so that the code doesn't have to explicitly be told how many variables you have. For example sum(par) is an operation that doesn't need to be told the length of par.
카테고리
도움말 센터 및 File Exchange에서 Solver Outputs and Iterative Display에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!