CodexBloom - Programming Q&A Platform

Inconsistent results with MATLAB 'polyfit' when fitting large datasets in R2023b

👀 Views: 263 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
polyfit data-fitting numerical-methods MATLAB

I'm trying to implement I've tried everything I can think of but This might be a silly question, but I'm currently working on fitting a polynomial to a large dataset using MATLAB's `polyfit` function, but I'm experiencing inconsistent results when using datasets with more than 10,000 points... For instance, when I fit a cubic polynomial to my data, the coefficients often seem to fluctuate significantly between runs, even though the input data remains unchanged. Here's a snippet of my code: ```matlab x = linspace(0, 10, 10000); % 10,000 data points noise = randn(size(x)) * 0.1; % Add some noise y = 3 * x.^3 - 2 * x.^2 + x + noise; % Synthetic polynomial data % Fitting a cubic polynomial p = polyfit(x, y, 3); ``` When I run this code multiple times, the output coefficients vary quite a bit: ```matlab % First run: p = 3.0001 -1.9999 1.0003 % Second run: p = 2.9998 -2.0005 1.0000 ``` I've tried adjusting the noise level and even switched the polynomial degree but the inconsistency persists. I also attempted to use `polyval` to evaluate the fit, and the output appears correct, but it's the coefficients that seem unreliable. Is there something inherent to `polyfit` that leads to such variability with large datasets, or are there specific best practices I should follow for ensuring stability in my fitting results? Any insights or suggestions would be greatly appreciated! Has anyone else encountered this? I've been using Matlab for about a year now. I've been using Matlab for about a year now.