fft2 — Compute two-dimensional discrete Fourier transforms in MATLAB and RunMat.
fft2(X) computes the two-dimensional discrete Fourier transform of X. It is equivalent to applying fft along the first two dimensions, with shape and ordering behavior consistent with MATLAB and RunMat.
Syntax
Y = fft2(X)
Y = fft2(X, SIZE)
Y = fft2(X, M, N)Inputs
X- Type
Any- Required
- Yes
- Description
- Input array.
SIZE- Type
NumericArray- Required
- No
- Description
- RunMat-only scalar N or two-element [M N] size shorthand.
M- Type
NumericScalar- Required
- No
- Description
- Positive output row count for transform.
N- Type
NumericScalar- Required
- No
- Description
- Positive output column count for transform.
Returns
Y- Type
NumericArray- Description
- 2-D complex Fourier spectrum output.
Errors
RunMat:fft2:ArgCount- When
- More than three input arguments are supplied.
- Message
fft2: invalid argument count
RunMat:fft2:InvalidLength- When
- Length/size arguments are invalid.
- Message
fft2: invalid transform length argument
RunMat:fft2:InvalidSizeVector- When
- Single SIZE argument is invalid.
- Message
fft2: invalid size vector argument
Provider and fusion contract
The provider hook advertises f32 and f64 floating precision with MATLAB-style input shape semantics; integer and logical behavior follows the separate documented conversion or exact-reordering rules.
This operation is a fusion boundary, not an elementwise or reduction kernel. No fused FFT kernel is advertised, and provider launch details remain internal.
Behavior
fft2(X) transforms along the first and second dimensions that have size greater than one.
fft2(X, M, N) zero-pads or truncates X to M rows and N columns before evaluating the 2-D transform.
RunMat extension: fft2(X, SIZE) accepts a two-element vector (or scalar) specifying the transform lengths when RunMat extensions are enabled.
Real inputs produce complex outputs; complex inputs are transformed element-wise with no additional conversion.
Higher-dimensional inputs are transformed slice-by-slice across trailing dimensions, matching MATLAB behaviour.
MATLAB-compatible M and N controls are positive integer scalars. Empty and zero transform sizes are separately gated RunMat extensions.
GPU arrays execute on-device when the provider advertises the fft_dim hook; otherwise RunMat gathers the data and performs the transform on the host using rustfft.
GPU execution
Runs two provider-backed fft_dim passes when available; otherwise the runtime gathers to the host.
GPU residency
You usually do NOT need to call gpuArray manually. The fusion planner and native acceleration layer keep tensors on the GPU when a provider offers FFT kernels. If the provider lacks fft_dim, RunMat gathers inputs, evaluates the FFT pair on the host, and returns a MATLAB-compatible complex tensor. You can still use gpuArray for explicit residency control, particularly when interoperating with MATLAB code that expects it.
Examples
Computing the 2-D FFT of a small matrix
X = [1 2; 3 4];
Y = fft2(X)Expected output:
Y =
10 + 0i -2 + 0i
-4 + 0i 0 + 0iZero-padding an image patch before fft2
patch = [1 0 1; 0 1 0; 1 0 1];
F = fft2(patch, 8, 8)Specifying transform lengths with a size vector
X = rand(4, 6);
F = fft2(X, [8 4]); % requires RunMat extension modeUsing fft2 on gpuArray data
G = gpuArray(rand(256, 256));
F = fft2(G);
R = gather(F)Applying fft2 to each slice of a 3-D volume
V = rand(64, 64, 10);
spectra = fft2(V)Verifying fft2 against sequential fft calls
X = rand(5, 7);
sequential = fft(fft(X, [], 1), [], 2);
direct = fft2(X)Using fft2 with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how fft2 changes the result.
Run a small fft2 example, explain the result, then change one input and compare the output.
FAQ
Is fft2(X) the same as fft(fft(X, [], 1), [], 2)?⌄
Yes. RunMat literally performs the two sequential transforms so the results match MATLAB exactly.
How do zero-length transform sizes behave?⌄
MATLAB-compatible mode requires positive M and N. RunMat extension mode can use 0 to produce a zero-sized complex tensor.
Can I use a single scalar for the size argument?⌄
In RunMat extension mode, fft2(X, K) is shorthand for fft2(X, [K K]). The documented compatibility forms are fft2(X) and fft2(X,M,N).
What happens when X has more than two dimensions?⌄
RunMat applies fft2 to every 2-D slice defined by the first two dimensions, leaving higher dimensions untouched.
Do I get complex outputs for real inputs?⌄
Always. Even when the imaginary parts are zero, outputs are stored as complex tensors to mirror MATLAB semantics.
Will fft2 run on the GPU automatically?⌄
Yes if the input's owning provider implements fft_dim for its storage class. Otherwise RunMat gathers to the host, performs the transform with rustfft, and restores the result to that provider.
Does fft2 normalise the output?⌄
No. Like MATLAB, the forward FFT leaves scaling untouched; use ifft2 for the inverse with 1/(M*N) scaling.
Can I mix [] with explicit sizes (e.g., fft2(X, [], 128))?⌄
This is a RunMat extension. MATLAB-compatible mode requires positive scalar M and N values.
Related Math functions
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
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
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 fft2 is executed, line by line, in Rust.
- View the source for fft2 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.