atan2 — Quadrant-aware inverse tangent atan2(y, x) in MATLAB and RunMat.
theta = atan2(y, x) computes the four-quadrant inverse tangent of point (x, y). The result is in radians over (-pi, pi], with element-wise scalar expansion behavior that matches MATLAB and RunMat.
Syntax
Z = atan2(Y, X)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
Y | Any | Yes | — | Real single/double y-coordinate; integer, logical, and character forms are RunMat-only extensions. |
X | Any | Yes | — | Real single/double x-coordinate; integer, logical, and character forms are RunMat-only extensions. |
Returns
| Name | Type | Description |
|---|---|---|
Z | NumericArray | Quadrant-aware inverse tangent result. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:atan2:InvalidInput | An input cannot be interpreted as supported real numeric data. | atan2: invalid input |
RunMat:atan2:ComplexUnsupported | At least one operand is complex. | atan2: complex inputs are not supported |
RunMat:atan2:SizeMismatch | Input operands are not broadcast-compatible. | atan2: size mismatch |
RunMat:atan2:Internal | Internal gather/conversion/allocation/provider flow failed. | atan2: internal error |
RunMat:atan2:TooManyOutputs | More than one output is requested. | atan2: too many output arguments |
How atan2 works
- Documented inputs are real
singleordoublescalars, vectors, matrices, and N-D arrays. MATLAB-style implicit expansion applies when every paired dimension is equal or one dimension is singleton. atan2treatsyas the numerator andxas the denominator:atan2(Y, X)equalsatan(Y ./ X)but keeps the correct quadrant and handles zero denominators.- RunMat can additionally accept all eight real integer classes, logical arrays, and character arrays when RunMat extensions are enabled. These are classified extensions, not MATLAB-compatible forms; integer storage remains authoritative until one explicit binary64 computation boundary.
- Complex inputs are not supported; MATLAB raises an error and RunMat matches that behaviour.
- MATLAB deliberately differs from IEEE 754 for a negative-zero denominator: both
atan2(0,-0)andatan2(-0,-0)return positive zero. RunMat applies that rule on host, provider, and fused execution paths while preserving the negative-zero result ofatan2(-0,0). atan2(NaN, x)oratan2(y, NaN)returnsNaN; inputs containingInfcombinations follow IEEE-754 quadrant semantics exactly like MATLAB.- The output has the broadcasted input size. Double inputs return double; single inputs return single; a mixed single/double call computes with double operands and casts the result to single.
Does RunMat run atan2 on the GPU?
When both operands already reside on the GPU and the active provider implements the elem_atan2 hook, RunMat executes the operation entirely on the device without reformatting buffers.
If shapes require implicit expansion or the provider lacks elem_atan2, RunMat transparently gathers both tensors to the host, computes the result with the reference CPU implementation, and restores it to the first resident input's owning provider.
Native single storage remains single. Mixed single/double inputs compute in double and return single, matching the documented MATLAB binary element-wise rule.
Fusion-aware expressions (for example, sin(atan2(y, x))) can still emit a combined WGSL kernel; the emitted expression includes MATLAB's positive-zero override for a negative-zero denominator.
GPU memory and residency
RunMat's planner keeps tensors on the GPU whenever profitable. Explicit gpuArray calls are optional—use them only when you need to control residency for interoperability. When elem_atan2 is unavailable, broadcasting is required, or an admitted extension uses typed integer/logical storage, RunMat gathers through the owning provider, computes on the CPU, and restores the result to that provider.
Examples
Computing the polar angle of a point
theta = atan2(4, 3)Expected output:
theta = 0.9273Determining quadrants for a vector of coordinates
Y = [-1 0 1];
X = [-1 -1 -1];
angles = atan2(Y, X)Expected output:
angles = [-2.3562 3.1416 2.3562]Broadcasting a scalar denominator across a matrix
A = [1 2 3; 4 5 6];
angles = atan2(A, 2)Expected output:
angles =
0.4636 0.7854 0.9828
1.1071 1.1903 1.2490Handling zero numerators and signed zeros
theta = atan2([0 -0], [-2 0])Expected output:
theta = [pi 0]Executing atan2 on the GPU
Gy = gpuArray([1 1; -1 -1]);
Gx = gpuArray([1 -1; 1 -1]);
angles_gpu = atan2(Gy, Gx);
angles = gather(angles_gpu)Expected output:
angles =
0.7854 2.3562
-0.7854 -2.3562Computing four-quadrant angles from character codes
theta = atan2('A', 100)Expected output:
theta = 0.5764Using atan2 with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how atan2 changes the result.
Run a small atan2 example, explain the result, then change one input and compare the output.
FAQ
What is the range of values returned by atan2?⌄
Angles are given in radians and span the open/closed interval (-pi, pi]. Use rad2deg if you prefer degrees.
Can I supply complex inputs?⌄
No. MATLAB raises an error for complex inputs, and so does RunMat. Convert complex data to magnitude/phase first if needed.
Does atan2 preserve the shape of the inputs?⌄
Yes. After implicit expansion, the output shape matches the broadcasted size of Y and X.
How are logical or character inputs handled?⌄
They are not documented MATLAB atan2 inputs. With RunMat extensions enabled, logical values map to 0 and 1, character arrays use their Unicode code points, and typed integers cross an explicit binary64 computation boundary.
What happens when x is zero?⌄
atan2 still returns a finite result using the sign of y. For example, atan2(1, 0) returns pi/2, and atan2(-1, 0) returns -pi/2.
Are GPU and CPU results identical?⌄
RunMat enforces the MATLAB negative-zero exception in its host, supplied provider, and fusion implementations. Normal floating-point results can still differ by routine provider precision and rounding.
How can I compute angles in degrees?⌄
Call rad2deg(atan2(y, x)) or multiply the result by 180/pi.
Related Math functions
Trigonometry
acos · acosh · asin · asinh · atan · atanh · cos · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh
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
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
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
Open-source implementation
Unlike proprietary runtimes, every RunMat function is open-source. Read exactly how atan2 is executed, line by line, in Rust.
- View the source for atan2 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.