How to solve betainc error in Polyfitn extension (by John D'Errico)?
3 次查看(过去 30 天)
显示 更早的评论
When using 'just' four point for linear regression in polyfitn, I am often getting this error:
Error using betainc X must be in the interval [0,1].
Error in polyfitn (line 270) polymodel.p = betainc(polymodel.DoF./(t.^2 + polymodel.DoF),polymodel.DoF/2,1/2);
But four points should be enough to fit the plane in 3D space. And I am getting this error also when using more points.
What does this error message means? How to deal with it? Because I have never experienced this error using official polyfit in 2D space.
Thank you!
2 个评论
John D'Errico
2025-3-6
Yes. I never saw the question. Too easy to blink some days, and miss something.
回答(1 个)
Raag
2025-3-6
Hi ZuzkaT,
The error you are encountering occurs because the ‘polyfitn’ function attempts to calculate error estimates for your fitted model. When you use exactly the minimum number of data points required for the fit, there is no extra data to estimate variability. This situation leads to an internal division by zero (0/0), which causes the ‘betainc’ function to receive an invalid value.
To address this, instead of using just the minimum number of points, supply additional data so the function can properly compute the error estimates.
Below is a simple example to illustrate the difference between using the minimal data which will trigger the error and using extra data which should work fine:
% Example 1: Minimal data (expected to trigger the error)
x_min = [1; 2];
y_min = [3; 4];
try
P_min = polyfitn(x_min, y_min, 1);
catch ME
fprintf('Expected error with minimal data:\n%s\n\n', ME.message);
end
% Example 2: Extra data points (should work without error)
x_extra = [1; 1; 2; 2];
y_extra = [3; 3; 4; 4];
P_extra = polyfitn(x_extra, y_extra, 1);
disp('Fitted model with extra data:');
disp(P_extra);
Output:

For a better understanding of the above solution, refer to the following MATLAB documentations:
1 个评论
John D'Errico
2025-3-6
Yes. It appears to be a 0/0 issue, caused when the code is called with insufficient data to estimate a variance.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Special Functions 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!