log2 — Compute base-2 logarithms element-wise in MATLAB and RunMat.
Y = log2(X) computes the base-2 logarithm of each element of X. Real and complex single inputs preserve single precision, while double inputs preserve double precision. When RunMat extensions are enabled, integer, logical, and character inputs are additionally accepted and promoted to double.
Syntax
Y = log2(X)Inputs
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
X | Any | Yes | — | Numeric, logical, char, or complex input. |
Returns
| Name | Type | Description |
|---|---|---|
Y | NumericArray | Elementwise base-2 logarithm result. |
Errors
| Identifier | When | Message |
|---|---|---|
RunMat:log2:InvalidInput | Input cannot be interpreted as numeric, logical, char, or complex data. | log2: invalid input |
RunMat:log2:Internal | Internal tensor construction or provider interaction failed. | log2: internal error |
RunMat:gpu:ProviderOwnershipMismatch | A resident input has no exact owning provider. | log2: resident input has no exact owning provider |
RunMat:log2:GpuComplexInputRequired | Explicitly resident real input would require a complex result. | log2: real gpuArray input must be explicitly complex when the result can be complex |
How log2 works
- Only the one-output
Y = log2(X)form is implemented; the two-output mantissa/exponent form is not available yet. log2operates element-wise and preserves the input shape.- When RunMat extensions are enabled, logical inputs convert to doubles (
true → 1.0,false → 0.0) before the logarithm is applied. - When RunMat extensions are enabled, character arrays are interpreted as their numeric code points and return dense double tensors of the same shape.
- When RunMat extensions are enabled, integer inputs are promoted to double before the logarithm is applied.
log2(0)returns-Inf; positive infinity staysInf;NaNpropagates unchanged.- Negative real values promote to complex results:
log2([-1 1])returns[0 + i·π/ln(2), 0]. - Complex inputs follow MATLAB's definition
log2(z) = log(z) / ln(2)and clamp subnormal imaginary parts to zero for readability.
Does RunMat run log2 on the GPU?
RunMat Accelerate keeps supported real inputs on their exact GPU owner when the active provider implements unary_log2. If the provider lacks the hook, automatic residency may fall back to a host result, while explicit residency is restored to the originating owner. Real GPU inputs that require complex promotion must be made explicitly complex before calling log2.
GPU memory and residency
Automatically resident inputs may gather to the host when the provider cannot perform the operation. Explicit gpuArray inputs use the same exact device owner for supported fallback restoration. If a real GPU input would require promotion to a complex result, RunMat reports that the input must be explicitly complex instead of silently returning a host value.
Examples
Computing base-2 logarithms of powers of two
values = [1 2 4 8];
powers = log2(values)Expected output:
powers = [0 1 2 3]Understanding how log2 handles zero
z = log2(0)Expected output:
z = -InfWorking with negative inputs using complex results
neg = [-1 -2];
out = log2(neg)Expected output:
out = [0.0000 + 4.5324i 1.0000 + 4.5324i]Checking power-of-two exponents for matrix sizes
A = [64 128; 256 512];
exponents = log2(A)Expected output:
exponents = [6 7; 8 9]Running log2 on GPU-resident data
G = gpuArray([1 4 16 64]);
result = log2(G);
host = gather(result)Expected output:
host = [0 2 4 6]Computing base-2 logarithms of character codes
C = 'ABC';
values = log2(C)Expected output:
values = [6.0224 6.0444 6.0661]Using log2 with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how log2 changes the result.
Run a small log2 example, explain the result, then change one input and compare the output.
FAQ
When should I use log2 instead of log or log10?⌄
Use log2 when you care about binary scalings—such as signal-processing bit widths, FFT sizes, or exponent analysis. Use log (natural logarithm) for exponential growth/decay and log10 for decimal magnitudes.
What happens if an element is zero?⌄
log2(0) returns negative infinity (-Inf), matching MATLAB behavior.
How does log2 handle negative real numbers?⌄
Negative values promote to complex numbers with an imaginary component of π/ln(2). This preserves phase information instead of producing NaN.
Can I pass complex inputs to log2?⌄
Yes. Complex scalars and tensors are handled as log(z) / ln(2), matching MATLAB exactly.
Does the GPU implementation support complex outputs?⌄
The device hook currently operates on real buffers. A real GPU input that would require complex promotion raises an error asking for an explicitly complex GPU input; RunMat does not silently gather that explicit input and change its residency contract.
Is log2 numerically stable for very small or large values?⌄
The implementation preserves single precision for single inputs and double precision for double inputs. Integer, logical, and character extensions are promoted to double. Tiny imaginary components introduced by floating-point evaluation may be normalized to zero.
Related Math functions
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 · 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 log2 is executed, line by line, in Rust.
- View the source for log2 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.