关于不使用polyfit和polyval实现P3(x)曲线拟合的技术问询
polyfit/polyval Hey there! Let's walk through how to recreate your cubic fitting workflow without using MATLAB's built-in polyfit and polyval functions. We'll rely on the underlying linear algebra of least-squares fitting instead.
Step-by-Step Explanation
First, remember that a cubic polynomial has the form:
$$p(x) = p_0 + p_1x + p_2x^2 + p_3x^3$$
To find the coefficients $[p_0, p_1, p_2, p_3]$, we need to solve the least-squares problem, which boils down to solving the normal equations:
$$X^T X \mathbf{p} = X^T \mathbf{y}$$
where $X$ is the design matrix, with each row corresponding to $[1, x_i, x_i^2, x_i^3]$ for your data points $x_i$.
Full Replaced Code
Here's the code that replaces your original implementation, with comments explaining each new part:
n = input('Enter a value: '); if(n < 3) fprintf('Enter a different value larger than 3\n'); return; % Exit early if input is invalid end % Generate original data (same as your code) x = 1:n; y = -0.3*x + 2*randn(1,n); % -------------------------- % Manual cubic fitting part % -------------------------- % Construct the design matrix X: each row is [1, x_i, x_i^2, x_i^3] X = [ones(n,1), x', (x').^2, (x').^3]; % Solve for polynomial coefficients using least squares (normal equations) % Using backslash operator is more stable than inv(X'*X)*(X'*y) p = (X' * X) \ (X' * y); % Calculate fitted values manually (equivalent to polyval) y_fit = X * p; % Optional: Approximate error bounds (similar to delta from polyval) % Calculate residuals residuals = y - y_fit; % Estimate variance of residuals sigma2 = sum(residuals.^2)/(n - 4); % n - number of coefficients (4 for cubic) % Calculate covariance matrix of coefficients cov_p = sigma2 * inv(X' * X); % Compute delta (standard error for each fitted point) delta = sqrt(diag(X * cov_p * X')); % -------------------------- % Plotting (same as your original code, updated title for accuracy) plot(x,y,'bo') hold on plot(x,y_fit,'r-') % Optional: Uncomment to add error bars for delta % errorbar(x, y_fit, delta, 'r--') title('Cubic-Fit Output') legend('Data','Cubic Fit') hold off
Key Notes
- The design matrix
Xis the core of replacingpolyfit—it maps our input x-values to the polynomial basis functions. - Using MATLAB's backslash operator
\for solving the normal equations is numerically more stable than computing the inverse directly withinv(). - We've included an optional section to calculate
delta(error bounds) similar to whatpolyvalreturns with theSstructure, using basic linear algebra for residual variance and covariance.
内容的提问来源于stack exchange,提问作者Onur Ege Unaldi

