conv2 — Compute two-dimensional convolution in MATLAB and RunMat.
conv2 performs two-dimensional linear convolution in direct and separable forms. The documented numeric, logical, and eight fixed-width integer classes are accepted. Any single numeric input selects single output; otherwise the result is double. Integer input crosses the explicit floating-point computation boundary.
Syntax
C = conv2(A, B)
C = conv2(A, B, shape)
C = conv2(hcol, hrow, A)
C = conv2(hcol, hrow, A, shape)Inputs
A- Type
Any- Required
- Yes
- Description
- First matrix input.
B- Type
Any- Required
- Yes
- Description
- Second matrix input.
shape- Type
StringScalar- Required
- No
- Default
"full"- Description
- Output shape: full, same, or valid.
hcol- Type
Any- Required
- Yes
- Description
- Column-vector kernel component.
hrow- Type
Any- Required
- Yes
- Description
- Row-vector kernel component.
A- Type
Any- Required
- Yes
- Description
- Input matrix.
Returns
C- Type
NumericArray- Description
- 2-D convolution result.
Errors
RunMat:conv2:ArgCount- When
- More than four inputs are provided.
- Message
conv2: expected at most four input arguments
RunMat:conv2:ShapeInvalid- When
- Shape argument is not full/same/valid.
- Message
conv2: shape argument must be the string 'full', 'same', or 'valid'
RunMat:conv2:InvalidInput- When
- An operand is not numeric/logical scalar/vector/matrix compatible.
- Message
conv2: unsupported input type
Forms and dimensions
conv2(A,B) computes full two-dimensional convolution. same selects the central result with the dimensions of A; even-sized kernels use the top-left alignment in each even dimension. valid keeps only complete kernel overlaps. A scalar is a 1-by-1 matrix.
conv2(hcol,hrow,A) applies the outer-product kernel of two vectors to A, without conjugating either factor. The optional final shape selector also accepts full, same, or valid. RunMat uses a column pass followed by a row pass when checked factor balancing and intermediate ranges permit it. Otherwise, it forms the kernel and uses the general convolution path.
An empty operand gives an empty full or valid result. Same mode retains the signal matrix shape and fills its empty-kernel result with zeros.
For nonempty matrices, full mode has dimensions size(A)+size(B)-1; valid mode has dimensions size(A)-size(B)+1 when the kernel fits along both axes. The separable kernel has numel(hcol) rows and numel(hrow) columns.
Classes and placement
Logical inputs promote to double. Explicitly complex inputs remain complex even if all computed imaginary components are zero. Integer operands, including mixed classes and host complex integer storage, convert independently to the selected floating result class before arithmetic.
Same-owner, same-device real floating operands may use a native provider conv2d hook. Its output is admitted only with the required class, shape, owner, device, and distinct live allocation. Other supported resident values gather through their owners and eligible floating results return to the first owner. Typed complex integer host data works; the current provider ABI cannot encode typed complex-integer resident buffers.
Convolution terminates fusion plans. The direct host form uses nested-loop convolution. The separable host form uses two one-dimensional passes when numerically admitted, with the general kernel as its fallback.
Numerical comparisons should account for accumulation order, scale, and precision. Example comparison tolerances of 1e-9 for double and 1e-3 for single are illustrative guidance, not universal error bounds for arbitrary inputs.
Examples
Smooth an image patch
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.1111Full convolution of two 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 4Preserve image 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 -13Valid sliding-window convolution
block = magic(4);
kernel = ones(2);
valid = conv2(block, kernel, 'valid')Expected output:
valid =
34 26 34
32 34 36
34 42 34Use column and row kernel factors
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 =
15 6 -15
28 8 -28
27 6 -27Convolve resident arrays
G = gpuArray(rand(128, 128));
H = gpuArray([1 2 1; 0 0 0; -1 -2 -1]);
gx = conv2(G, H, 'same');
result = gather(gx)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 all three shape modes?⌄
Yes. Full, same, and valid select the output extent; same uses the documented even-kernel alignment.
How do I use the separable form?⌄
Call conv2(hcol,hrow,A) with an optional final shape. RunMat applies the column and row factors in separate passes when their numerical ranges permit it; otherwise it uses the outer-product kernel.
What happens if an input is empty?⌄
Full and valid produce an empty result. Same preserves the first signal matrix dimensions with zero values when the kernel is empty.
Do logical inputs work?⌄
Yes. They are promoted to double before convolution.
Will the result stay on the GPU?⌄
A same-owner, same-device real floating pair can use a provider conv2d hook. Other supported resident values gather through their owners and eligible floating results return to the first owner. Host typed complex integers work; the current provider ABI cannot encode resident typed complex integers.
What does conv2 compute?⌄
It flips the kernel over both axes and sums products at each overlapping location. For correlation without flipping, use filter2.
When is the separable form faster?⌄
For an admitted two-pass calculation, each output accumulates contributions from the column and row factors separately rather than from every coefficient of their outer product. This reduces arithmetic for larger rank-one kernels. Intermediate allocation, output shape, numerical fallback, and device transfers also affect elapsed time; a speedup is not guaranteed.
Should I use conv2, filter2, or imfilter?⌄
Use conv2 for convolution, filter2 for correlation, and imfilter for image-specific boundary modes such as replicate, symmetric, and circular. Symmetric kernels can give the same convolution and correlation result.
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 · 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
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
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Interpolation
griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline
Integer Division
Source you can read
Every RunMat function's source is public. 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 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.