MATLAB: Can I use the Jacobian provided by ‘lsqnonlin’ to compute the confidence intervals using ‘nlparci’

confidence intervalsjacobianlsqnonlinnlparciStatistics and Machine Learning Toolbox

The function 'nlparci' accepts as input the Jacobian of the regressing function at the optimal point. In the explanation of this function, it is only mentioned the Jacobian which is obtained from 'nlinfit'. Nevertheless, 'lsqnonlin' also provides a Jacobian output. Is it correct to use the Jacobian from 'lsqnonlin' directly in 'nlparci'?

Best Answer

Yes, you can use it but see Matt J's warning about using bounded constraints.
[estParams,~,residual,~,~,~,jacobian] = lsqnonlin();
CI = nlparci(estParams,residual,'jacobian',jacobian);
An alternative is to calculate the covariance matrix to calculate the confidence intervals directly (shown below). There are typically very small differences in the results between the two methods.
lastwarn(''); %Clear warning memory
alpha = 0.05; %significance level
df = length(residual) - numel(estParams); %degrees of freedom
crit = tinv(1-alpha/2,df); %critical value
covm = inv(jacobian'*jacobian) * var(residual); %covariance matrix
[~, warnId] = lastwarn; %detect if inv threw 'nearly singular' warning.
covmIdx = sub2ind(size(covm),1:size(covm,1),1:size(covm,2)); %indices of the diag of covm
CI = nan(numel(estParams),2);
if ~strcmp(warnId, 'MATLAB:nearlySingularMatrix')
CI(:,1) = estParams - crit * sqrt(covm(covmIdx));
CI(:,2) = estParams + crit * sqrt(covm(covmIdx));
end