abs — Absolute value and complex magnitude for scalars and arrays in MATLAB and RunMat.
y = abs(x) returns absolute values for real inputs and magnitudes for floating complex inputs. For arrays, abs is applied element-wise and preserves the input shape. All eight integer classes preserve their input class and use saturating arithmetic at the signed minimum.
Syntax
Y = abs(X)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
X | Any | Yes | — | Real numeric input or floating complex input; logical and character forms are RunMat-only extensions. |
Returns
| Name | Type | Description |
|---|---|---|
Y | NumericArray | Absolute value or magnitude. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:abs:InvalidInput | Input is not supported real numeric, floating complex, or declared extension data. | abs: invalid input |
RunMat:abs:Internal | Internal tensor conversion/allocation/provider interaction failed. | abs: internal error |
RunMat:abs:TooManyOutputs | More than one output is requested. | abs: too many output arguments |
How abs works
- Real scalars, vectors, matrices, and N-D tensors are mapped to their element-wise absolute values.
- Complex single and double inputs return the magnitude
sqrt(real(x).^2 + imag(x).^2)in the corresponding real floating class; typed complex integer inputs are rejected. - Integer scalars and full arrays preserve exact class and shape. Unsigned values are unchanged, signed values are negated, and
abs(intmin(class))saturates tointmax(class). - Sparse single and double inputs retain their CSC structure and native class. Exact sparse integer storage is available only in RunMat compatibility mode.
- Logical inputs are a declared RunMat-only extension and are promoted to doubles (
true → 1.0,false → 0.0). - Character arrays are a declared RunMat-only extension and are converted to double code-point magnitudes.
- String arrays are not supported and raise an error.
- RunMat does not yet implement the documented duration, table, or timetable overloads.
- NaN values remain NaN; the function does not change IEEE NaN propagation rules.
Does RunMat run abs on the GPU?
Hook available: The absolute value is computed directly on the device with no host transfers.
Hook missing or unsupported dtype: RunMat gathers through authoritative native storage, performs the CPU absolute value logic, and restores the result to the input handle's owning provider. Integer fallback preserves exact class, including 64-bit values.
When a provider supports complex-interleaved storage, abs computes magnitudes on the device and returns a real GPU tensor with the original shape.
GPU memory and residency
You usually do not need to call gpuArray explicitly. RunMat's fusion planner and Accelerate layer track residency automatically, keeping tensors on the GPU whenever device execution is beneficial. Explicit gpuArray/gather calls remain available for MATLAB compatibility or when you need deterministic residency control (e.g., integrating with third-party GPU kernels).
Examples
Getting the absolute value of a scalar
y = abs(-42)Expected output:
y = 42Taking the absolute value of a vector
v = [-2 -1 0 1 2];
result = abs(v)Expected output:
result = [2 1 0 1 2]Measuring complex magnitudes
z = [3+4i, 1-1i];
magnitudes = abs(z)Expected output:
magnitudes = [5 1.4142]Working with matrices on an accelerator
G = randn(2048, 2048, "gpuArray");
positive = abs(G)Computing magnitudes of logical values
mask = logical([0 1 0; 1 0 1]);
numeric = abs(mask)Expected output:
numeric = [0 1 0; 1 0 1]Computing magnitudes of character codes
c = 'ABC';
codes = abs(c)Expected output:
codes = [65 66 67]Chaining abs inside fused expressions
x = linspace(-2, 2, 5);
y = abs(x) + x.^2Using abs with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how abs changes the result.
Run a small abs example, explain the result, then change one input and compare the output.
FAQ
Does abs change NaN values?⌄
No. abs(NaN) returns NaN, consistent with IEEE arithmetic and MATLAB behaviour.
What happens to complex numbers?⌄
RunMat returns the magnitude sqrt(real(x).^2 + imag(x).^2), identical to MATLAB.
Can I call abs on string arrays?⌄
No. abs accepts supported numeric inputs; RunMat compatibility mode additionally enables logical and character extensions.
Does abs work with sparse arrays?⌄
Yes for real sparse single and double inputs, which retain sparse CSC storage. RunMat compatibility mode also preserves exact typed sparse integers.
Is GPU execution exact?⌄
Device execution follows IEEE semantics for the provider's precision (single or double). F32 backends may incur small rounding differences compared to CPU double.
How do I keep results on the GPU?⌄
Avoid calling gather unless you need host data. The planner keeps device tensors resident whenever possible.
Does abs allocate new memory?⌄
Yes. The builtin returns a new tensor; fusion may in-place combine kernels to reduce allocations when safe.
Can I use abs with logical masks?⌄
Only in RunMat compatibility mode. The extension promotes logical values to double 0 or 1 before applying abs.
Related Math functions
Elementwise
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
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 abs is executed, line by line, in Rust.
- View the source for abs 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.