polyval — Evaluate polynomials at specified points in MATLAB and RunMat.
polyval(p, x) evaluates polynomial p at each element of x. Coefficient ordering, optional prediction-interval forms, and output-shape behavior follow MATLAB semantics.
Syntax
y = polyval(p, x)
y = polyval(p, x, S)
y = polyval(p, x, S, mu)
[y, delta] = polyval(p, x)
[y, delta] = polyval(p, x, S)
[y, delta] = polyval(p, x, S, mu)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
p | Any | Yes | — | Polynomial coefficient vector. |
x | Any | Yes | — | Evaluation points. |
S | Any | No | — | Optional polyfit statistics structure. |
S | Any | No | — | Optional polyfit statistics structure (or []). |
mu | Any | No | — | Optional centering/scaling vector [mean, std]. |
Returns
| Name | Type | Description |
|---|---|---|
y | Any | Evaluated polynomial values at x. |
delta | Any | Prediction interval values when S is supplied. |
Returned values from polyval depend on how many outputs the caller requests.
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:polyval:InvalidArgument | Option arguments (S/mu/output arity) are malformed or unsupported. | polyval: invalid argument |
RunMat:polyval:InvalidInput | Polynomial coefficients or evaluation points cannot be interpreted as numeric inputs. | polyval: invalid input |
RunMat:polyval:Internal | Runtime fails while building output tensors, deltas, or provider fallbacks. | polyval: internal runtime failure |
How polyval works
- Accepts scalar, vector, or N-D coefficient inputs that have at most one non-singleton dimension.
- Logical and integer coefficients are promoted to double precision; complex coefficients are kept exactly.
- When
pandxare real-valued and a provider is registered, RunMat issues a Horner-series GPU kernel via RunMat Accelerate. Mixed or complex inputs fall back to the reference CPU implementation, with purely real outputs re-uploaded to the device when residency makes sense. polyval(p, x, [], mu)applies centering and scaling parameters frompolyfit, evaluating the polynomial at(x - mu(1)) / mu(2).[y, delta] = polyval(p, x, S, mu)computes prediction intervals using the structureSproduced bypolyfit. RunMat mirrors MATLAB rules:Smust contain the fieldsR,normr, anddf, and the interval collapses to zeros whendf <= 0ornormr == 0.- Empty inputs yield empty outputs; an empty coefficient vector represents the zero polynomial.
- MATLAB-compatible errors are raised for non-numeric inputs, invalid
muvectors, or malformedSstructures.
Does RunMat run polyval on the GPU?
When a GPU provider is active, RunMat first attempts to evaluate the polynomial in device memory using a dedicated Horner kernel. Coefficients and inputs are uploaded automatically when required. If the call requests complex arithmetic, prediction intervals, or otherwise falls outside the GPU kernel’s contract, RunMat gathers to the host, executes the CPU implementation, and (for real-valued results) pushes the output back to the GPU so downstream kernels retain residency.
Examples
Evaluating a polynomial at scalar points
p = [2 -3 5]; % 2x^2 - 3x + 5
y = polyval(p, 4)Expected output:
y = 21Evaluating across a vector of inputs
p = [1 0 -2 1];
x = linspace(-2, 2, 5);
y = polyval(p, x)Expected output:
y = [ -3 2 1 0 5 ]Evaluating a polynomial over a matrix grid
[X, Y] = meshgrid(-1:1);
Z = polyval([1 -3 2], X + Y)Expected output:
Z =
12 6 2
6 2 0
2 0 0Using centering and scaling parameters from polyfit
x = -2:2;
noise = 0.05 * randn(size(x));
[p, S, mu] = polyfit(x, sin(x) + noise, 3);
y = polyval(p, x, [], mu)Expected output:
% y closely matches sin(x) + noise with polynomial smoothingComputing prediction intervals with polyfit output
[p, S, mu] = polyfit((0:10)', exp((0:10)'/10), 3);
[y, delta] = polyval(p, 5, S, mu)Expected output:
% y is the fitted value at x = 5
% delta is the 1σ prediction interval (standard error)Handling complex coefficients and inputs
p = [1+2i, -3, 4i];
z = [-1+1i, 0, 1-2i];
y = polyval(p, z)Expected output:
% Complex results that agree with MATLAB's polyvalEvaluating on a gpuArray input
x = gpuArray.linspace(-1, 1, 2048);
p = [1 0 1];
y = polyval(p, x); % Runs on the GPU for real-valued inputsExpected output:
y is a gpuArray because the result is real-valued.How RunMat validates polyval
polyval evaluates the polynomial using the standard Horner recurrence, the same scheme MATLAB and NumPy's polyval use. The CPU implementation covers real and complex coefficients plus the polyfit prediction-interval form. The GPU path has a dedicated Horner kernel for real inputs and falls back to CPU for complex or prediction-interval calls.
- Implementation: crates/runmat-runtime/src/builtins/math/poly/polyval.rs
- Parity test: polyval unit tests
- Tolerance: 1e-9 (f64), 1e-3 (f32)
See Correctness & Trust for the full methodology and coverage table.
Using polyval with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how polyval changes the result.
Run a small polyval example, explain the result, then change one input and compare the output.
FAQ
Do coefficients need to be a row vector?⌄
No. They can be row or column vectors (or any N-D shape with a single non-singleton dimension). The output always matches the shape of x.
What kinds of inputs are accepted?⌄
Numeric scalars, vectors, matrices, N-D arrays, logical arrays, and complex data are all accepted. Logical and integer inputs are promoted to double precision automatically.
How do centering (mu) parameters work?⌄
RunMat mirrors MATLAB: the polynomial is evaluated at (x - mu(1)) / mu(2). The mu vector must contain at least two finite values, and the scale mu(2) must be non-zero.
Why does [y, delta] = polyval(...) require the structure S?⌄
The prediction interval comes from the QR factorization stored in S by polyfit. The structure must include the fields R, df, and normr; without them the interval cannot be computed.
What happens when df <= 0 or normr == 0?⌄
The prediction interval collapses to zeros (RunMat matches MATLAB and Octave here). This typically occurs when the fit is exact or when there are insufficient degrees of freedom.
Can I keep results on the GPU?⌄
Yes. RunMat re-uploads real-valued results to the active provider after the host evaluation. Complex outputs stay on the host until providers add complex buffer uploads.
Does polyval support sparse inputs?⌄
Not yet. Dense inputs (including gpuArray tensors) are supported today. Sparse support will arrive once RunMat's sparse infrastructure stabilises.
What does polyval do?⌄
— polyval(p, x) evaluates the polynomial whose coefficients are stored in p at every point in x. Coefficients are listed highest degree first, so p = [2 -3 5] represents 2*x^2 - 3*x + 5. The output has the same shape as x.
How does polyval evaluate a polynomial?⌄
— polyval uses Horner's method (nested multiplication), which rewrites p(1)*x^n + p(2)*x^(n-1) + ... + p(end) as ((p(1)*x + p(2))*x + p(3))*x + .... Horner's method needs only n multiplications and n additions and is more numerically stable than computing each power of x explicitly.
How do I use polyval with polyfit?⌄
— Fit a polynomial with polyfit, then evaluate it on a smooth grid with polyval. For example:
p = polyfit(x, y, 3);
xfine = linspace(min(x), max(x), 200);
yfit = polyval(p, xfine);
plot(x, y, 'o', xfine, yfit, '-');When polyfit returns [p, S, mu], pass them through (polyval(p, xfine, S, mu)) to get centring-aware evaluation and prediction intervals.
Related Math functions
Elementwise
abs · angle · complex · conj · double · exp · expm1 · factorial · gamma · heaviside · hypot · imag · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · sign · single · sqrt · times
Trigonometry
acos · acosh · asin · asinh · atan · atan2 · atanh · cos · cosd · cosh · deg2rad · rad2deg · sin · sind · sinh · tan · tand · tanh
Reduction
all · any · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · mean · median · min · nnz · prod · std · sum · trapz · var
Structure
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how polyval is executed, line by line, in Rust.
- View the source for polyval in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is an open-source runtime that executes MATLAB-syntax code blazing on any GPU. It is licensed under the Apache 2.0 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.