hypot — Compute element-wise Euclidean norms with hypot in MATLAB and RunMat.
z = hypot(x, y) computes sqrt(|x|.^2 + |y|.^2) element-wise using overflow-resistant arithmetic. Single/double inputs, implicit expansion, complex handling, NaN precedence, and output shape follow MATLAB semantics. Integer, logical, and character operands are RunMat extensions.
Syntax
R = hypot(X, Y)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
X | Any | Yes | — | Left operand. |
Y | Any | Yes | — | Right operand. |
Returns
| Name | Type | Description |
|---|---|---|
R | NumericArray | Elementwise Euclidean norm result. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:hypot:InvalidInput | Input value cannot be converted to supported numeric form. | hypot: invalid input |
RunMat:hypot:SizeMismatch | Operands are not broadcast-compatible. | hypot: size mismatch |
RunMat:hypot:Internal | Internal gather/provider/tensor construction failed. | hypot: internal error |
How hypot works
- Real inputs return non-negative results even when the operands are negative; all-single inputs preserve single precision and other supported real numeric combinations return double.
- Complex arguments are converted to their magnitudes before forming
sqrt(|x|.^2 + |y|.^2), matching MATLAB's definition since R2020b. - Scalars broadcast across the other operand when shapes are compatible; otherwise an error is raised.
- Empty inputs propagate emptiness according to MATLAB's size rules.
Infoperands returnInf;NaNoperands propagateNaN.
Does RunMat run hypot on the GPU?
Hook available and shapes match: the Euclidean norm executes in a single fused GPU kernel.
Hook missing or implicit expansion required: RunMat downloads each resident operand non-destructively through its owner, computes the MATLAB-compatible result on the host, and restores the result to the selected owner when its physical precision preserves the public output class; otherwise the correctly typed result remains on the host.
Fusion-enabled expressions: the fusion planner can emit a WGSL hypot(a, b) node so long as the active provider marks the group as supported; otherwise the execution seamlessly falls back to the host path.
Providers can implement elem_hypot by emitting a single WGSL/compute shader that calls hypot(a, b); the included WGPU backend demonstrates this pattern.
GPU memory and residency
Manual gpuArray calls are typically unnecessary. RunMat's planner keeps tensors on the GPU when profitable. When elem_hypot is explicitly unsupported or implicit expansion requires the host path, RunMat downloads non-destructively through each input owner and restores the result when the selected output precision can be preserved; otherwise it returns the correctly typed host result. Source handles remain resident.
Examples
Computing the hypotenuse of two scalars
result = hypot(3, 4)Expected output:
result = 5Using hypot with vectors and implicit expansion
x = [-3, 0, 4];
y = 4;
norms = hypot(x, y)Expected output:
norms = [5 4 5]Calculating per-element distances between two matrices
X = [1 2; 3 4];
Y = [0 1; 1 0];
dist = hypot(X, Y)Expected output:
dist = [1.0000 2.2361; 3.1623 4.0000]Working with complex numbers
a = [1+2i, 3-4i];
b = [2-1i, -1+1i];
mag = hypot(a, b)Expected output:
mag = [3.1623 5.1962]Computing hypotenuse values from character codes
codes = hypot('A', zeros(1, 1))Expected output:
codes = 65.0000Executing hypot on GPU arrays
Gx = gpuArray([3 4; 5 12]);
Gy = gpuArray([4 3; 12 5]);
distance_gpu = hypot(Gx, Gy);
distance = gather(distance_gpu)Expected output:
distance = [5 5; 13 13]Using hypot with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how hypot changes the result.
Run a small hypot example, explain the result, then change one input and compare the output.
FAQ
Does hypot overflow for large inputs?⌄
No. Like MATLAB, RunMat uses a stable algorithm that scales the operands to avoid overflow and underflow. Very large inputs return finite results when mathematically possible.
What happens when the inputs are negative?⌄
hypot always returns a non-negative result because it squares the magnitudes first. Signs on the inputs only matter when NaN or Inf is involved.
Can I mix real and complex inputs?⌄
Yes. Complex inputs are converted to magnitudes before forming the norm, so you can freely combine real, complex, and logical data.
Does hypot accept logical or character arrays?⌄
Yes, when RunMat extensions are enabled. Logical values map to 0 and 1, while character arrays use their Unicode code points as doubles.
How does broadcasting work?⌄
The function applies MATLAB's implicit expansion: singleton dimensions expand to match the other operand. If a non-singleton dimension differs, RunMat raises a dimension mismatch error.
Are GPU results identical to CPU results?⌄
For double precision providers the results match bit-for-bit. Single precision providers (e.g., wgpu in F32 mode) may differ by typical floating-point rounding.
What if only one operand lives on the GPU?⌄
The runtime gathers the GPU operand, computes the norm on the host, and continues execution. Future providers may implement scalar expansion directly on the device.
Does hypot allocate a new array?⌄
Yes. The builtin returns a fresh tensor. Fusion may elide intermediate buffers when the expression participates in a larger GPU kernel.
How can I compute the magnitude of a vector of components?⌄
Use hypot repeatedly: hypot(x, hypot(y, z)) computes the Euclidean norm of (x, y, z) element-wise without manual squaring.
Related Math functions
Elementwise
abs · angle · bsxfun · complex · conj · double · erf · erfcinv · exp · expm1 · factorial · flintmax · gamma · gammaln · heaviside · 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
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 hypot is executed, line by line, in Rust.
- View the source for hypot 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.