sum — Add array elements along selected dimensions.
sum(X) adds elements along the first non-singleton dimension. A dimension, dimension vector, or 'all' selects other reduction axes; missing-data and output-class controls select the calculation's treatment of NaNs and numeric class.
Syntax
S = sum(A)
S = sum(A, dim)
S = sum(A, "all")
S = sum(A, missingflag)
S = sum(A, outtype)
S = sum(A, dim, missingflag)All supported sum forms
S = sum(A)
S = sum(A, dim)
S = sum(A, "all")
S = sum(A, missingflag)
S = sum(A, outtype)
S = sum(A, dim, missingflag)
S = sum(A, missingflag, dim)
S = sum(A, vecdim)
S = sum(A, options...)Inputs
A- Type
Any- Required
- Yes
- Description
- Input array.
dim- Type
Any- Required
- No
- Default
[]- Description
- Dimension selector or vector of dimensions.
all- Type
StringScalar- Required
- No
- Default
"all"- Description
- Reduce across all dimensions.
missingflag- Type
StringScalar- Required
- No
- Default
"includemissing"- Description
- Missing-data handling mode: "includemissing" or "omitmissing".
outtype- Type
StringScalar- Required
- No
- Default
"default"- Description
- Output class specifier: "double", "default", or "native".
options- Type
Any- Required
- Variadic
- Description
- Admitted dimension, missing-data, and output-class controls.
Returns
S- Type
NumericArray- Description
- Sum reduction result.
Errors
RunMat:sum:InvalidArgument- When
- Dimension, missing-data flag, or output class argument grammar is invalid.
- Message
sum: invalid argument
RunMat:sum:InvalidInput- When
- Input values cannot be converted to supported sum reduction domains.
- Message
sum: invalid input
RunMat:sum:Internal- When
- Reduction execution fails due to conversion, provider, allocation, or coercion operations.
- Message
sum: internal reduction failure
Dimensions and missing values
For an m-by-n matrix, sum(X) returns a 1-by-n row of column sums. sum(X,2) returns an m-by-1 column of row sums. A dimension vector, such as [1 3], reduces each selected axis while preserving the others. sum(X,'all') reduces every element to one scalar.
The default 'includenan' policy propagates NaNs in an affected slice. 'omitnan' excludes NaNs, returning zero when a slice contains no retained observations. Empty reduction slices also return zero in the selected output shape.
Logical input values enter the sum as zero or one and return double by default. Complex floating inputs are summed componentwise. A dimension beyond ndims(X) leaves input elements unchanged.
Numeric classes
Ordinary sums accumulate in double before applying the requested output class. The default mode preserves single outputs and returns double for double, integer, and logical inputs. Explicit 'double' returns double even when a selected dimension lies beyond the stored rank. 'native' preserves the input numeric class; native integer accumulation instead uses exact typed storage and saturating arithmetic where required.
sum does not support a 'like' prototype option. Use 'native' or 'double' to select the output class.
GPU and fused execution
Eligible resident reductions use provider reduce_sum_dim or reduce_sum operations. NaN omission and unsupported provider forms can gather through the exact owner; native integer reductions use distinct resident operations. Ordinary integer and single sums require double accumulation: providers with a supported double route can keep the calculation resident, while others use the exact-owner gather rather than losing precision or applying native integer saturation. Output-class adaptation restores through the input's provider when that provider supports the class, and may return a host value for an automatically placed result when it does not.
The shared fusion planner can prepare an eligible real floating sum as a reduction kernel. The catalog marks sum as a fusion candidate, not as an always-fused operation. Automatic placement can choose a GPU when beneficial, and explicit gpuArray remains available.
Examples
Column and row sums
A = [1 2 3; 4 5 6];
colSums = sum(A);
rowSums = sum(A, 2);
colSums
rowSumsExpected output:
colSums = [5 7 9]
rowSums = [6; 15]Sum across multiple dimensions
B = reshape(1:24, [3 4 2]);
collapse = sum(B, [1 3])Expected output:
collapse = [48 66 84 102]Ignore NaN observations
values = [1 NaN 3];
total = sum(values, 'omitnan')Expected output:
total = 4Native resident sum
G = gpuArray(single([1 2 3]));
result = sum(G, 'all', 'native');
gathered = gather(result)Expected output:
gathered = 6Sum every element
C = [1 2 3; 4 5 6];
grandTotal = sum(C, 'all')Expected output:
grandTotal = 21Keep an integer result
ints = int32([100 200 300]);
total = sum(ints, 'native')Expected output:
total = 600Using sum with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how sum changes the result.
Run a small sum example, explain the result, then change one input and compare the output.
FAQ
When should I use sum?⌄
Use sum to add elements along one dimension, several selected dimensions, or across the whole array.
Does sum produce double by default?⌄
Double, integer, and logical inputs return double by default; single inputs return single. Use 'double' to request double explicitly, including for a no-op dimension, or 'native' to keep the input numeric class.
What shape does sum(A) return?⌄
The first non-singleton dimension becomes size one. On an m-by-n matrix, the result is a 1-by-n row of column sums.
How do I choose reduction dimensions?⌄
Pass a positive dimension such as sum(A,2), a dimension vector, or 'all' for every element.
What does an all-NaN slice return with omitnan?⌄
It returns zero because no observations remain to add.
How do I preserve an integer class?⌄
Pass 'native'. It uses exact typed integer accumulation. The older 'like' prototype form is not currently accepted.
Related Math functions
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 · trapz · var
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
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 sum is executed, line by line, in Rust.
- View the source for sum 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.