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.1, Nov 17, 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
    • 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

pcg — Solve a positive-definite linear system with conjugate gradients.

Solve dense, sparse CSC, or callable systems with a shared precision-preserving host recurrence, optionally using reusable matrix or callable inverse-action preconditioners. The full compatibility contract remains incomplete.

Syntax

[x,flag,relres,iter,resvec] = pcg(A,b,tol,maxit,M1,M2,x0)

Inputs

A
Type
Any
Required
Yes
Default
—
Description
Square dense or sparse single or double coefficient matrix, or callable mapping an n-by-1 vector to a matching vector.
b
Type
NumericArray
Required
Yes
Default
—
Description
Column right-hand side matching the class and order of A.
args
Type
Any
Required
Variadic
Default
—
Description
Optional tol, maxit, M1, M2, and x0 positions. Preconditioners are selected callable inverse actions or reusable native-class dense/CSC matrix solves; general CSC factors require unrestricted host allocation.
NameTypeRequiredDefaultDescription
AAnyYes—Square dense or sparse single or double coefficient matrix, or callable mapping an n-by-1 vector to a matching vector.
bNumericArrayYes—Column right-hand side matching the class and order of A.
argsAnyVariadic—Optional tol, maxit, M1, M2, and x0 positions. Preconditioners are selected callable inverse actions or reusable native-class dense/CSC matrix solves; general CSC factors require unrestricted host allocation.

Returns

x
Type
NumericArray
Description
Approximate solution column vector.
flag
Type
NumericScalar
Description
Convergence flag: 0 converged, 1 iteration limit, 2 unusable numerical preconditioner result, 3 stagnation, 4 breakdown. Language and execution-control failures remain errors.
relres
Type
NumericScalar
Description
Relative residual of the returned iterate.
iter
Type
NumericScalar
Description
Iteration at which the returned iterate was computed.
resvec
Type
NumericArray
Description
Residual norm history, including the initial residual.
NameTypeDescription
xNumericArrayApproximate solution column vector.
flagNumericScalarConvergence flag: 0 converged, 1 iteration limit, 2 unusable numerical preconditioner result, 3 stagnation, 4 breakdown. Language and execution-control failures remain errors.
relresNumericScalarRelative residual of the returned iterate.
iterNumericScalarIteration at which the returned iterate was computed.
resvecNumericArrayResidual norm history, including the initial residual.

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

Errors

RunMat:pcg:InvalidInput
When
Input count, dimensions, tolerance, iteration count, or sparse CSC topology are invalid.
Message
pcg: invalid input
RunMat:pcg:UnsupportedInput
When
Coefficient, class combination, or preconditioner requires an unavailable route.
Message
pcg: unsupported input form
RunMat:pcg:HostAllocation
When
The selected host policy cannot admit exact scratch or retained result storage.
Message
pcg: host admission failed
IdentifierWhenMessage
RunMat:pcg:InvalidInputInput count, dimensions, tolerance, iteration count, or sparse CSC topology are invalid.pcg: invalid input
RunMat:pcg:UnsupportedInputCoefficient, class combination, or preconditioner requires an unavailable route.pcg: unsupported input form
RunMat:pcg:HostAllocationThe selected host policy cannot admit exact scratch or retained result storage.pcg: host admission failed

Matrices and callable operators

pcg(A,b) uses conjugate gradients when A is a square dense or sparse CSC matrix with native single or double real or complex coefficients and b is a matching column vector. Dense storage is borrowed in column-major order; sparse storage is multiplied directly without densifying A.

A can also be a function handle implementing the matrix-vector product. Each call receives an n-by-1 vector and must return an n-by-1 vector with the same single/double precision and real/complex domain as b. The solver invokes the callback asynchronously and keeps its input and result rooted across suspension.

tol, maxit, and x0 occupy the usual optional positions. Empty placeholders select the defaults. The default tolerance is 1e-6 for double and 1e-3 for single; default maxit is min(size(A,1),20). The initial guess defaults to zero.

Up to five outputs are [x,flag,relres,iter,resvec]. resvec starts with norm(b-A*x0). A nonconverged result returns the iterate with the lowest computed residual norm.

M1 and M2 can be function handles implementing inverse actions, or matching dense/CSC matrix preconditioners. The solver applies M1 first and M2 second; empty placeholders omit either action. Triangular matrices remain borrowed; a general matrix is factored once and reused, not multiplied into the residual. General sparse preconditioners support finite managed allocation with individually admitted sparse fill growth and reusable solve workspace.

Current boundaries

Matrix coefficients, vectors, and triangular factors must have matching native floating classes. Mixed coefficient/vector classes, gpuArray inputs, and distributed inputs are not silently converted or transferred. Callable outputs are checked on every application rather than inferred from the first result.

Matrix and callable solves support finite managed host allocation for up to five outputs, subject to the selected callback's own admission. Solver scratch and output backing are admitted before iteration. Each callback receives an independently claimed vector, so retaining an input cannot alias or retain mutable recurrence scratch. Callback captures and source authority remain owned by the execution context.

Callback vector and result copies, solution publication and residual-history copies check execution authority in bounded chunks and use the context's CPU cooperation budget. A suspended output constructor owns its exact backing until completion or drop. A receipt-less solve or factor cannot continue if its allocation scope becomes finite; it must fail rather than publish unclaimed storage.

The implemented flags are 0 (converged), 1 (iteration limit), 2 (a numerical preconditioner failure or non-finite inverse-action result), 3 (stagnation), and 4 (breakdown or nonpositive curvature). Flag 2 retains the best iterate, its relative residual and the residual history computed before the failed action. Callback language errors, invalid classes/shapes, allocation denial, cancellation and authority changes remain errors; the solver does not retry a completed callback or turn those failures into a numerical flag.

Examples

Solve a sparse positive-definite system

A = sparse([4 1; 1 3]); b = [1; 2]; [x,flag,relres] = pcg(A,b);

Use a matrix-vector callback and a diagonal inverse action

A = [4 1; 1 3]; b = [1; 2]; Afun = @(v) A*v; Mfun = @(v) [v(1)/4; v(2)/3]; [x,flag,relres] = pcg(Afun,b,1e-8,20,Mfun);

Using pcg with coding agents

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

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

Related Linalg functions

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 · qr · qz · rsf2csf · schur · svd

Structure

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

Solve

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

Ops

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

Source you can read

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

  • View the source for pcg 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
  • Matrices and callable operators
  • Current boundaries
  • Examples
  • Solve a sparse positive-definite system
  • Use a matrix-vector callback and a diagonal inverse action
  • Using pcg with coding agents
  • Related Linalg functions
  • Factor
  • Structure
  • Solve
  • Ops
  • Source you can read
  • About RunMat