rem — Compute the truncation-based remainder of compatible real values.
rem applies truncation-based remainder semantics with implicit expansion, exact fixed-width integer handling, supported containers, and validated provider execution.
Syntax
R = rem(A, B)Inputs
A- Type
Any- Required
- Yes
- Description
- Real numeric, logical, character, table, timetable, or duration dividend.
B- Type
Any- Required
- Yes
- Description
- Compatible real divisor or scalar expansion operand.
Returns
R- Type
Any- Description
- Element-wise remainder result, retaining the supported numeric class or container.
Errors
RunMat:rem:InvalidInput- When
- An operand is complex or is not a supported real numeric, logical, character, table, timetable, or duration value.
- Message
rem: invalid input
RunMat:rem:InvalidArgument- When
- The invocation does not contain exactly two inputs.
- Message
rem: invalid argument
RunMat:rem:SizeMismatch- When
- Numeric operands are not broadcast-compatible or tabular operands do not have compatible variables.
- Message
rem: array sizes are not compatible for implicit expansion
Definition and signs
The quotient formula describes the mathematical result, not the floating-point implementation. RunMat reduces represented operands without forming a large rounded quotient, so cases such as rem(1e17, 11) retain the exact remainder 10.
Floating roundoff near integer multiples is compensated using a bounded normalized equality check: the nearest integer quotient must reproduce the normalized dividend exactly when multiplied by the aligned divisor. This makes rem(3 * 0.7, 0.7) zero. Two whole-number floating operands bypass this correction. The public MATLAB documentation describes roundoff compensation; this specific rule is RunMat's independently implemented policy.
rem(A, B) computes A - B .* fix(A ./ B) element by element. The result is zero or has the dividend's sign. This differs from mod whenever a nonzero result combines operands with different signs.
For floating operands, a zero divisor produces NaN. A finite dividend and infinite divisor return the dividend; an infinite dividend with a finite divisor and NaN inputs produce NaN. Fixed-width integer storage cannot represent NaN, so an integer zero-divisor element returns integer zero.
Classes, shapes, and containers
Real scalar, vector, matrix, and N-D operands use implicit expansion. Double and single operands retain their floating class, with single taking precedence when the floating inputs differ. Logical and character operands enter the double domain; characters contribute their Unicode code points. Complex and sparse inputs are not accepted.
Matching fixed-width integer operands retain their class and use exact native storage. A documented scalar-double pairing is accepted where the integer class permits it. Wide integers are not converted through binary64.
Tables and timetables apply rem to corresponding variables and retain their container metadata. A numeric scalar can be applied to every variable. Duration operands are measured in days for the calculation and return a duration with the source display format.
Accelerated and distributed execution
Compatible resident operands use the exact provider that owns both handles. Provider results are accepted only when shape, storage, precision, owner, device, and aliasing satisfy the catalog contract. A typed unsupported response uses one host fallback and restores the result to that owner when its physical representation can be preserved; other provider errors remain visible.
Compatible expressions may use the elementwise fusion definition. Distributed inputs currently use the declared materialization path before the same canonical operation is applied; this preserves values and classes without claiming a partition-local binary map that the execution service does not yet provide.
Examples
Preserve large remainders and compensate a near multiple
large = rem(1e17, 11);
near = rem(3 * 0.7, 0.7);Preserve single precision across pages
x = reshape(single([1.25 -0.75 3.25 -2.75]), [2 1 2]);
y = rem(x, single(2));Compute a positive remainder
r = rem(17, 5)Expected output:
r = 2Follow the dividend's sign
values = [-7 -3 4 9];
r = rem(values, 4)Expected output:
r = [-3 -3 0 1]Use a negative divisor
r = rem(7, -4)Expected output:
r = 3Expand a column against a row
A = [-5; 8];
B = [3 4 5];
R = rem(A, B)Expected output:
R = [-2 -1 0; 2 0 3]Observe a floating zero divisor
R = rem([2 0 -2], 0)Expected output:
R = [NaN NaN NaN]Retain exact integer storage
A = uint64([0x0020000000000001u64, 0xFFFFFFFFFFFFFFFFu64]);
R = rem(A, uint64(2))Expected output:
R is uint64([1 1])Retain single precision
A = single([-3.5 4.5]);
R = rem(A, 2)Expected output:
R is single([-1.5 0.5])Apply remainder to table variables
T = table([5; 8], [7; 11], 'VariableNames', {'A', 'B'});
R = rem(T, 3)Expected output:
R retains A and B with values [2;2] and [1;2]Compute remainders of durations
A = hours([25 50]);
R = rem(A, hours(24))Expected output:
R = [01:00:00 02:00:00]Compute on resident values
G = gpuArray(-5:5);
R = gather(rem(G, 4))Expected output:
R = [-1 0 -3 -2 -1 0 1 2 3 0 1]Using rem with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how rem changes the result.
Run a small rem example, explain the result, then change one input and compare the output.
FAQ
How does rem differ from mod?⌄
rem rounds the quotient toward zero, so a nonzero result has the dividend's sign. mod rounds the quotient toward negative infinity, so its nonzero result has the divisor's sign.
What does a zero divisor return?⌄
Floating operands produce NaN. Exact fixed-width integer storage returns integer zero because its class has no NaN representation.
Does rem accept complex values?⌄
No. Both operands must be real.
Are integer values converted to double?⌄
No. Supported fixed-width integer forms retain their integer class and use exact native storage.
How are tables handled?⌄
The operation is applied variable by variable. Table and timetable identity, variable order, and timetable row-time metadata are retained.
What unit is used for duration and numeric combinations?⌄
Numeric values are interpreted as 24-hour days. The result is returned as a duration when either operand is a duration.
Will provider fallback lose residency?⌄
A semantically unsupported provider hook may use an owner-specific host fallback and restore the result. Malformed outputs and execution failures are errors, not fallback signals.
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 rem is executed, line by line, in Rust.
- View the source for rem 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.