RunMat
  • Pricing
RunMat
GitHub
GitHub
DownloadSign InTry in Browser
DesktopRuntimeServer
RunMat

Run math blazing fast

GitHubX (Twitter)LinkedIn

Company

  • About
  • Pricing
  • Contact

Explore

  • RunMat for academia
  • RunMat vs MATLAB Online
  • Benchmarks

Get product updates and release notes from the RunMat team.

© 2026 Dystr · Made withfor the scientific community.

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.

LicensePrivacy
/
See all docs
Builtin Reference
    • 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

conv2 — Compute two-dimensional convolution in MATLAB and RunMat.

conv2 performs two-dimensional linear convolution in direct and separable forms. MATLAB documents all eight integer classes, logical, single, double, and complex inputs; any single numeric input selects single output and every other combination returns double.

Syntax

C = conv2(A, B)
C = conv2(A, B, shape)
C = conv2(hcol, hrow, A)
C = conv2(hcol, hrow, A, shape)

Inputs

NameTypeRequiredDefaultDescription
AAnyYes—First matrix input.
BAnyYes—Second matrix input.
shapeStringScalarNo"full"Output shape: "full", "same", or "valid".
hcolAnyYes—Column vector kernel component.
hrowAnyYes—Row vector kernel component.
AAnyYes—Input matrix.

Returns

NameTypeDescription
CNumericArray2-D convolution result.

Errors

IdentifierWhenMessage
RunMat:conv2:ArgCountMore than four input arguments are provided.conv2: expected at most four input arguments
RunMat:conv2:ShapeInvalidShape argument is not one of full/same/valid.conv2: shape argument must be the string 'full', 'same', or 'valid'
RunMat:conv2:InvalidInputAn operand is not numeric/logical scalar/vector/matrix compatible.conv2: unsupported input type
RunMat:conv2:VectorRequiredSeparable hcol/hrow inputs are not vectors.conv2: vector input required
RunMat:conv2:MatrixRequiredInput matrix has non-singleton dimensions beyond 2-D.conv2: input must be 2-D
RunMat:conv2:ConversionInput conversion from logical/gpu tensor into host matrix domain fails.conv2: input conversion failed
RunMat:conv2:GatherFailedGPU input cannot be gathered for host fallback normalization.conv2: failed to gather GPU input
RunMat:conv2:BuildOutputOutput tensor allocation fails.conv2: failed to build tensor
RunMat:conv2:BuildComplexOutputOutput complex tensor allocation fails.conv2: failed to build complex tensor

How conv2 works

  • conv2(A, B) returns the full 2-D convolution of A and B.
  • conv2(A, B, 'same') slices the central part of the full convolution so the output matches the shape of A.
  • For even-sized kernels with 'same', alignment follows MATLAB's top-left convention in each even dimension.
  • conv2(A, B, 'valid') returns only those points where B overlaps A completely.
  • conv2(hcol, hrow, A) is syntactic sugar for conv2(hcol(:) * hrow(:)', A).
  • Direct A/B and separable u/v/A inputs accept every integer class, including mixed classes and complex integer storage. They convert to the selected floating output domain before multiplication and accumulation, so no integer overflow or saturation applies.
  • Scalars are treated as 1×1 matrices and preserve the orientation of the other input.
  • Empty inputs follow MATLAB’s rules: conv2([], X) and conv2(X, []) return empty matrices (or zero-sized slices for 'same').
  • Logical inputs are promoted to double precision before computation; explicit complex inputs remain complex even when the result has zero imaginary components; resident integer inputs gather exactly before conversion.

Does RunMat run conv2 on the GPU?

RunMat Accelerate invokes conv2d only for real floating handles owned by the same provider on the same device, and accepts the result only when its precision matches the single-dominant output rule. Otherwise each handle gathers through its owner, the host reference path computes true convolution, and an eligible real or complex result is restored to the first owner when that provider preserves its class.

Examples

Smoothing an image patch with a 3×3 averaging kernel

A = [1 2 3; 4 5 6; 7 8 9];
h = ones(3) / 9;
smoothed = conv2(A, h, 'same')

Expected output:

smoothed =
    1.3333    2.3333    1.7778
    3.0000    5.0000    3.6667
    2.6667    4.3333    3.1111

Computing the full convolution of two small kernels

K1 = [1 2; 3 4];
K2 = [1 1; 1 1];
C = conv2(K1, K2)

Expected output:

C =
     1     3     2
     4    10     6
     3     7     4

Extracting the same-sized result to preserve dimensions

edge = conv2([1 2 3; 4 5 6; 7 8 9], [1 0 -1; 1 0 -1; 1 0 -1], 'same')

Expected output:

edge =
     7     4    -7
    15     6   -15
    13     4   -13

Valid convolution for sliding-window statistics

block = magic(4);
kernel = ones(2);
valid = conv2(block, kernel, 'valid')

Expected output:

valid =
    34    26    34
    32    34    36
    34    42    34

Using the separable form with column and row vectors

hcol = [1; 2; 1];
hrow = [1 0 -1];
A = [3 4 5; 6 7 8; 9 10 11];
gx = conv2(hcol, hrow, A, 'same')

Expected output:

gx =
    27    -6   -27
    28    -8   -28
    15    -6   -15

Convolving gpuArray inputs with transparent fallbacks

G = gpuArray(rand(128, 128));
H = gpuArray([1 2 1; 0 0 0; -1 -2 -1]);
gx = conv2(G, H, 'same');
result = gather(gx)

How RunMat validates conv2

conv2 uses one formula-aligned implementation for direct (conv2(A, B)) and separable (conv2(u, v, A)) forms. Tests cover asymmetric kernels, even-kernel 'same' alignment, all shape modes, single and complex class retention, exact integer gathers, mixed providers, and resident fallback. Providers may supply a class-preserving native real-floating conv2d hook.

  • Implementation: crates/runmat-runtime/src/builtins/math/signal/conv2.rs
  • Parity test: conv2 unit tests
  • Tolerance: 1e-9 (f64), 1e-3 (f32)

See Correctness & Trust for the full methodology and coverage table.

Using conv2 with coding agents

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

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

FAQ

Does conv2 support the three MATLAB shape modes?⌄

Yes. Pass 'full', 'same', or 'valid' as the final argument and RunMat will mirror MATLAB’s output sizes and edge handling precisely.

How do I use the separable form?⌄

Call conv2(hcol, hrow, A) (optionally with a shape argument). RunMat converts the vectors into an outer-product kernel internally so it behaves exactly like MATLAB.

What happens if one input is empty?⌄

An empty input produces an empty output (or a zero-sized slice for 'same'). This follows MATLAB’s behaviour and avoids surprising dimension growth.

Do logical inputs work?⌄

Yes. Logical arrays are promoted to double precision before convolution so the result is numeric.

Will the result stay on the GPU?⌄

Same-owner, same-device real floating operands remain resident when a provider's conv2d hook returns the required class. Other resident operands gather independently, and eligible real or complex floating results return to the first owner. Typed complex integers work on the host, but the current provider ABI cannot encode typed complex-integer resident buffers.

What does conv2 actually compute?⌄

— Two-dimensional convolution. For every output pixel, conv2 flips the kernel B across both axes and sums the element-wise product of B with the corresponding neighbourhood of A. If you want correlation (no flip), use filter2 instead.

When is the separable form conv2(u, v, A) faster than conv2(A, B)?⌄

— Whenever the kernel is rank-1, i.e. B = u * v' for a column vector u and a row vector v. The separable form runs a 1-D column pass followed by a 1-D row pass, costing roughly O(n*(m+k)) operations instead of O(n*m*k) for the full 2-D kernel — a dramatic win for Gaussians, box filters, and Sobel components.

Should I use conv2, filter2, or imfilter?⌄

— Use conv2 for true convolution (the kernel is flipped); use filter2 for correlation with the same kernel (no flip); use imfilter when you need the Image Processing Toolbox's extended boundary handling ('replicate', 'symmetric', 'circular'). All three produce the same result when the kernel is symmetric.

Related Math functions

Signal

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

Elementwise

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

Trigonometry

acos · acosh · asin · asinh · atan · atan2 · 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

Rounding

ceil · fix · floor · mod · rem · round

Factor

chol · decomposition · eig · eigs · lu · qr · svd

Solve

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

Optim

coneprog · fminbnd · fminunc · fsolve · fzero · integral · linprog · lsqcurvefit · lsqnonlin · optimoptions · optimset · quad · secondordercone

Ops

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

Symbolic

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

Fft

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

Interpolation

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

Discrete

lcm · primes

Ode

ode15s · ode23 · ode45

Poly

polyder · polyfit · polyint · polyval · roots

Open-source implementation

Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how conv2 is executed, line by line, in Rust.

  • View the source for conv2 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.

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
  • How conv2 works
  • Does RunMat run conv2 on the GPU?
  • Examples
  • Smoothing an image patch with a 3×3 averaging kernel
  • Computing the full convolution of two small kernels
  • Extracting the same-sized result to preserve dimensions
  • Valid convolution for sliding-window statistics
  • Using the separable form with column and row vectors
  • Convolving gpuArray inputs with transparent fallbacks
  • How RunMat validates conv2
  • Using conv2 with coding agents
  • FAQ
  • Related Math functions
  • Signal
  • Elementwise
  • Trigonometry
  • Reduction
  • Structure
  • Rounding
  • Factor
  • Solve
  • Optim
  • Ops
  • Symbolic
  • Fft
  • Interpolation
  • Discrete
  • Ode
  • Poly
  • Open-source implementation
  • About RunMat