You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于不使用polyfit和polyval实现P3(x)曲线拟合的技术问询

Manual Cubic Polynomial Fitting Without 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 X is the core of replacing polyfit—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 with inv().
  • We've included an optional section to calculate delta (error bounds) similar to what polyval returns with the S structure, using basic linear algebra for residual variance and covariance.

内容的提问来源于stack exchange,提问作者Onur Ege Unaldi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:18:16