RunMat
  • Pricing
RunMat
GitHub
GitHub
Sign inTry in browser
DesktopRuntimePhysicsCADAdministrationAgent

Get RunMat updates

New releases, guides and examples.

Product+
  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download
Math+
  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting
Physics+
  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA
Industries+
  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance
Learn+
  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students
Compare+
  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons
Company+
  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms

Product

  • Runtime
  • GPU
  • Parallel
  • Compile
  • Interop and MEX
  • Simulation
  • MCAD
  • ECAD
  • Enterprise
  • AI integrations
  • Pricing
  • Download

Math

  • Signal processing
  • Linear algebra
  • Statistics
  • Curve fitting
  • Differential equations
  • Control systems
  • Optimization
  • Finance
  • Data and tables
  • Plotting

Physics

  • Simulation overview
  • Structural
  • Thermal
  • Electromagnetic
  • Joule heating
  • Thermal stress
  • Acoustics
  • Fluid flow
  • Conjugate heat transfer
  • Fluid–structure
  • What is FEA

Industries

  • Aerospace
  • Automotive and transportation
  • Defense
  • Electronics and semiconductors
  • Energy
  • Industrial machinery
  • Life sciences
  • Quantitative finance

Learn

  • Guides
  • Docs
  • Function reference
  • Language reference
  • Migration guide
  • Changelog
  • MATLAB Online
  • MATLAB AI agent
  • For students

Compare

  • RunMat vs MATLAB
  • RunMat vs Ansys
  • RunMat vs SOLIDWORKS
  • RunMat vs Altium
  • RunMat vs Cadence
  • RunMat vs COMSOL
  • RunMat vs Python
  • RunMat vs Julia
  • RunMat vs Physics AI
  • RunMat vs Octave
  • Benchmarks
  • MATLAB alternatives
  • All comparisons

Company

  • About
  • Blog
  • Contact
  • Source code↗
  • License
  • Privacy
  • Terms
GitHubXLinkedIn

© Dystr, Inc. · RunMat v0.7.2, Nov 26, 2026 ·

RunMat® is a registered trademark of Dystr, Inc. MATLAB® is a registered trademark of The MathWorks, Inc. RunMat is not affiliated with, endorsed by, or sponsored by The MathWorks, Inc.

/
See all docs
Builtin Reference
    • poly
    • polyder
    • polyfit
    • polyint
    • polyval
    • roots

polyfit — Fit least-squares polynomial coefficients and return fit diagnostics.

polyfit(X,Y,n) fits a degree-n polynomial using Householder QR. One or two outputs use the original X coordinates; requesting the third output fits in centered, scaled coordinates and returns that transformation as mu. Optional weights scale each residual.

Syntax

p = polyfit(X, Y, n)
p = polyfit(X, Y, n, weights)
[p, S] = polyfit(X, Y, n)
[p, S] = polyfit(X, Y, n, weights)
[p, S, mu] = polyfit(X, Y, n)
[p, S, mu] = polyfit(X, Y, n, weights)

Inputs

X
Type
Any
Required
Yes
Description
Real sample locations as a vector.
Y
Type
Any
Required
Yes
Description
Real or complex fitted observations as a vector.
n
Type
IntegerScalar
Required
Yes
Description
Nonnegative polynomial degree.
weights
Type
Any
Required
No
Description
Finite nonnegative weights, one per sample, with matching element count.
NameTypeRequiredDefaultDescription
XAnyYes—Real sample locations as a vector.
YAnyYes—Real or complex fitted observations as a vector.
nIntegerScalarYes—Nonnegative polynomial degree.
weightsAnyNo—Finite nonnegative weights, one per sample, with matching element count.

Returns

p
Type
Any
Description
Descending-power polynomial coefficient row vector.
S
Type
Any
Description
Fit statistics with R, df, and normr fields.
mu
Type
NumericArray
Description
Centering and scaling vector [mean(x), std(x)].
NameTypeDescription
pAnyDescending-power polynomial coefficient row vector.
SAnyFit statistics with R, df, and normr fields.
muNumericArrayCentering and scaling vector [mean(x), std(x)].

Returned values from polyfit depend on how many outputs the caller requests.

Errors

RunMat:polyfit:InvalidArgument
When
Degree or weight arguments are malformed or unsupported.
Message
polyfit: invalid argument
RunMat:polyfit:InvalidInput
When
Input vectors or values cannot be processed for polynomial fitting.
Message
polyfit: invalid input
RunMat:polyfit:Internal
When
Runtime fails while constructing fit outputs or provider payloads.
Message
polyfit: internal runtime failure
RunMat:polyfit:ProviderFailed
When
An owning acceleration provider returns malformed or nonfinite fit outputs.
Message
polyfit: invalid provider result
IdentifierWhenMessage
RunMat:polyfit:InvalidArgumentDegree or weight arguments are malformed or unsupported.polyfit: invalid argument
RunMat:polyfit:InvalidInputInput vectors or values cannot be processed for polynomial fitting.polyfit: invalid input
RunMat:polyfit:InternalRuntime fails while constructing fit outputs or provider payloads.polyfit: internal runtime failure
RunMat:polyfit:ProviderFailedAn owning acceleration provider returns malformed or nonfinite fit outputs.polyfit: invalid provider result

Samples and weighted fitting

X must be real and Y may be real or complex. Both must be nonempty coefficient-style vectors with the same number of elements; row, column, and singleton-extended vector shapes are accepted. The current runtime does not flatten arbitrary matrices or N-D arrays with multiple nonsingleton dimensions.

The optional fourth argument is a finite, real, nonnegative weight vector with one element per X/Y sample. It may differ from X in row/column orientation; the runtime checks element count rather than identical shape. Zero weights remove a sample's contribution to the weighted residual norm.

Fixed-width integer X, Y, and weights are separately gated RunMat extensions and require exact binary64 representability. Degree is an exact, nonnegative structural integer control; logical scalar degree and logical sample/weight arrays are also admitted by the current runtime.

Outputs and evaluation

The coefficient row p has n+1 entries in descending power order. With one or two outputs, p and S.R use the original X basis, so use polyval(p,X) or polyval(p,X,S). Requesting [p,S,mu] changes p and S.R to the centered, scaled basis; mu records mean(X) and scale(X), and polyval(p,X,[],mu) or polyval(p,X,S,mu) applies it during evaluation. S also contains degrees of freedom df and residual norm normr.

Host output storage is double or complex double. For requested outputs after p, S, and mu, RunMat supplies scalar zero padding. The fit uses numerical QR; rank-deficient or ill-conditioned data can affect accuracy.

Provider execution

Compatible resident X/Y/weight inputs may use the owning provider's polyfit hook. The current WGPU provider gathers within this hook and runs the shared Householder QR solver; the returned p, S, and mu are host values. Unsupported provider routes gather through the exact owners and run the same host solver.

The provider hook is real-data-only and requires compatible owners. It receives the requested coordinate basis explicitly, so provider and host fits return matching coefficient and QR bases. Complex Y, mixed locations, or incompatible inputs use the host route. Fitting is a fusion boundary; provider dispatch and host materialization still contribute to shared execution costs.

Examples

Fit a line through slightly noisy samples

x = 0:5;
noise = 0.05*[1 -1 0 1 -1 0];
y = 2.5*x + 1 + noise;
p = polyfit(x,y,1)

Expected output:

p is close to [2.5 1]

Reuse fit scaling when evaluating

x = -3:3;
y = x.^2-2*x+4;
[p,S,mu] = polyfit(x,y,2);
smoothed = polyval(p,x,[],mu)

Expected output:

smoothed matches y

Use S for prediction intervals

t = linspace(0,2*pi,25);
y = sin(t)+0.1*cos(3*t);
[p,S,mu] = polyfit(t,y,3);
[fitted,delta] = polyval(p,t,S,mu)

Expected output:

delta contains one value per fitted sample

Give central samples more weight

x = linspace(-1,1,7);
y = [1.1 0.4 0.2 0 0.1 0.5 1.4];
w = [1 2 2 4 2 2 1];
p = polyfit(x,y,2,w)

Expected output:

p is a three-coefficient row vector

Fit resident samples and receive host coefficients

x = gpuArray(linspace(-2,2,50));
y = (x-0.5).^3;
p = polyfit(x,y,3)

Expected output:

p is host-resident and close to [1 -1.5 0.75 -0.125]

Fit complex observations

x = 0:4;
y = exp(1i*x);
p = polyfit(x,y,2)

Expected output:

p contains complex coefficients

Using polyfit with coding agents

Open a RunMat example with live inputs, then ask the agent to explain how polyfit changes the result.

Run a small polyfit example, explain the result, then change one input and compare the output.

FAQ

How do I choose the degree?⌄

Supply a nonnegative integer. Degree relative to sample count controls conditioning; validate a chosen model against your data.

What do S and mu contain?⌄

S has R, df, and normr; mu contains centering mean and scale. Pass both to supported polyval prediction-interval forms.

How are weights used?⌄

Each nonnegative weight multiplies a squared residual. A zero weight removes that observation from the weighted fit.

Are outputs GPU-resident?⌄

No. The current provider hook and host fallback both produce host p, S, and mu values.

What if all sample locations coincide?⌄

A positive-degree fit is rank-deficient with coincident sample locations; a stable unique coefficient vector cannot be inferred from those samples.

Related Math functions

Poly

poly · polyder · polyint · polyval · roots

Elementwise

abs · angle · besselj · bsxfun · complex · conj · double · eps · erf · erfcinv · exp · expm1 · flintmax · gamma · gammaln · heaviside · hypot · imag · int16 · int32 · int64 · int8 · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · times · typecast · uint16 · uint32 · uint64 · uint8

Optim

acceptancesa · annealingboltz · annealingfast · coneprog · crossoverarithmetic · crossoverheuristic · crossoverintermediate · crossoverlaplace · crossoverscattered · crossoversinglepoint · crossovertwopoint · eqnproblem · EquationProblem.solve · EquationProblem.subsasgn · EquationProblem.subsref · evaluate · fgoalattain · fitscalingprop · fitscalingrank · fitscalingshiftlinear · fitscalingtop · fminbnd · fmincon · fminimax · fminsearch · fminunc · fseminf · fsolve · fzero · ga · gacreationlinearfeasible · gacreationnonlinearfeasible · gacreationsobol · gacreationuniform · gacreationuniformint · gaplotbestf · gaplotbestindiv · gaplotdistance · gaplotexpectation · gaplotgenealogy · gaplotmaxconstr · gaplotrange · gaplotscorediversity · gaplotscores · gaplotselection · gaplotstopping · integerConstraint · integral · intlinprog · linprog · lsqcurvefit · lsqlin · LsqlinWarmStart.subsasgn · LsqlinWarmStart.subsref · lsqnonlin · lsqnonneg · mutationadaptfeasible · mutationgaussian · mutationpositivebasis · mutationpower · mutationuniform · optimexpr · optimget · OptimizationConstraint.evaluate · OptimizationConstraint.subsasgn · OptimizationConstraint.subsref · OptimizationExitflag.double · OptimizationExitflag.eq · OptimizationExitflag.ne · OptimizationExitflag.string · OptimizationExpression.acos · OptimizationExpression.acosh · OptimizationExpression.acot · OptimizationExpression.acoth · OptimizationExpression.acsc · OptimizationExpression.acsch · OptimizationExpression.asec · OptimizationExpression.asech · OptimizationExpression.asin · OptimizationExpression.asinh · OptimizationExpression.atan · OptimizationExpression.atanh · OptimizationExpression.cat · OptimizationExpression.cos · OptimizationExpression.cosh · OptimizationExpression.cot · OptimizationExpression.coth · OptimizationExpression.csc · OptimizationExpression.csch · OptimizationExpression.ctranspose · OptimizationExpression.cumprod · OptimizationExpression.cumsum · OptimizationExpression.diag · OptimizationExpression.diff · OptimizationExpression.dot · OptimizationExpression.eq · OptimizationExpression.evaluate · OptimizationExpression.exp · OptimizationExpression.ge · OptimizationExpression.horzcat · OptimizationExpression.ldivide · OptimizationExpression.le · OptimizationExpression.log · OptimizationExpression.mean · OptimizationExpression.minus · OptimizationExpression.mldivide · OptimizationExpression.mpower · OptimizationExpression.mrdivide · OptimizationExpression.mtimes · OptimizationExpression.norm · OptimizationExpression.plus · OptimizationExpression.power · OptimizationExpression.prod · OptimizationExpression.rdivide · OptimizationExpression.reshape · OptimizationExpression.sec · OptimizationExpression.sech · OptimizationExpression.sin · OptimizationExpression.sinh · OptimizationExpression.sqrt · OptimizationExpression.subsasgn · OptimizationExpression.subsref · OptimizationExpression.sum · OptimizationExpression.tan · OptimizationExpression.tanh · OptimizationExpression.times · OptimizationExpression.trace · OptimizationExpression.transpose · OptimizationExpression.uminus · OptimizationExpression.uplus · OptimizationExpression.vertcat · OptimizationExpression.zeros · OptimizationExpression.zerosLike · OptimizationProblem.solve · OptimizationProblem.subsasgn · OptimizationProblem.subsref · OptimizationVariable.subsasgn · OptimizationVariable.subsref · optimoptions · optimplotconstrviolation · optimplotfirstorderopt · optimplotfunccount · optimplotfval · optimplotfvalconstr · optimplotmilp · optimplotstepsize · optimplotx · optimproblem · optimset · optimvar · optimwarmstart · particleswarm · patternsearch · psplotbestf · psplotbestx · psplotfuncount · psplotmaxconstr · psplotmeshsize · pswcreationuniform · pswplotbestf · quad · quadprog · QuadprogWarmStart.subsasgn · QuadprogWarmStart.subsref · saplotbestf · saplotbestx · saplotf · saplotstopping · saplottemperature · saplotx · savemilpsolutions · secondordercone · selectionremainder · selectionroulette · selectionstochunif · selectiontournament · selectionuniform · simulannealbnd · solve · surrogateopt · surrogateoptplot · temperatureboltz · temperatureexp · temperaturefast

Trigonometry

acos · acosd · acosh · acotd · acscd · asecd · asin · asind · asinh · atan · atan2 · atan2d · atand · atanh · cos · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh

Reduction

all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · median · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · nnz · prod · rms · std · sum · trapz · var

Structure

bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm

Bitwise

bitand · bitcmp · bitget · bitor · bitset · bitshift · bitxor · swapbytes

Signal

blackman · butter · buttord · cheb2ord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · resample · sawtooth · sinc · spectrogram · square · tripuls · unwrap · upsample · zplane

Rounding

ceil · fix · floor · mod · rem · round

Factor

chol · decomposition · decomposition.ctranspose · decomposition.mldivide · decomposition.mrdivide · decomposition.mtimes · decomposition.rdivide · decomposition.subsref · decomposition.times · decomposition.uminus · decomposition.uplus · eig · eigs · gmres · ichol · ilu · lu · ordeig · ordqz · ordschur · pcg · qr · qz · rsf2csf · schur · svd

Solve

cond · det · inv · linsolve · norm · null · pinv · rank · rcond · rref · vecnorm

Ops

cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose

Symbolic

digits · int · limit · piecewise · sym · syms · vpa

Discrete

factor · factorial · gcd · isprime · lcm · primes

Fft

fft · fft2 · fftn · fftshift · ifft · ifft2 · ifftn · ifftshift

Interpolation

griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline

Integer Division

idivide

Ode

ode15s · ode23 · ode45 · odeset

Source you can read

Every RunMat function's source is public. Read exactly how polyfit is executed, line by line, in Rust.

  • View the source for polyfit in Rust on GitHub
  • Learn how the RunMat runtime works
  • Found a bug? Open an issue with a minimal reproduction.

About RunMat

RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.

  • RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
  • Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.

Getting started · Benchmarks · Pricing

Download RunMat

Download RunMat for full performance, or use RunMat in your browser for zero setup.

Download RunMatOpen Sandbox
On this page
  • Syntax
  • Inputs
  • Returns
  • Errors
  • Samples and weighted fitting
  • Outputs and evaluation
  • Provider execution
  • Examples
  • Fit a line through slightly noisy samples
  • Reuse fit scaling when evaluating
  • Use S for prediction intervals
  • Give central samples more weight
  • Fit resident samples and receive host coefficients
  • Fit complex observations
  • Using polyfit with coding agents
  • FAQ
  • Related Math functions
  • Poly
  • Elementwise
  • Optim
  • Trigonometry
  • Reduction
  • Structure
  • Bitwise
  • Signal
  • Rounding
  • Factor
  • Solve
  • Ops
  • Symbolic
  • Discrete
  • Fft
  • Interpolation
  • Integer Division
  • Ode
  • Source you can read
  • About RunMat