sum!
sum!(r, A)
Sum elements of A
over the singleton dimensions of r
, and write results to r
.
Examples
-
Sum elements of a vector and store the result in another vector:
julia> A = [1, 2, 3, 4, 5]; julia> r = similar(A); julia> sum!(r, A) 5-element Array{Int64,1}: 1 3 6 10 15
This example computes the cumulative sum of the elements in vector
A
and stores the result in vectorr
. -
Sum elements of a matrix along the rows:
julia> A = [1 2 3; 4 5 6; 7 8 9]; julia> r = similar(A, 1, size(A, 2)); julia> sum!(r, A) 1×3 Array{Int64,2}: 12 15 18
It calculates the sum of each row of matrix
A
and stores the resulting row vector inr
. - Compute column-wise sum of a matrix:
julia> A = [1 2 3; 4 5 6; 7 8 9]; julia> r = similar(A, size(A, 1), 1); julia> sum!(r, A) 3×1 Array{Int64,2}: 12 15 18
This example computes the sum of each column of matrix
A
and stores the resulting column vector inr
.
Common mistake example:
julia> A = [1 2 3; 4 5 6; 7 8 9];
julia> r = [0, 0, 0];
julia> sum!(r, A)
ERROR: DimensionMismatch("output array has wrong dimensions for sum")
In this case, the output array r
has the wrong dimensions to store the result of the sum operation. It's important to ensure that the size and dimensions of r
match the expected result based on the dimensions of A
.
See Also
abs2, beta, binomial, ceil, cell, cross, ctranspose, ctranspose!, cummin, cumprod, cumprod!, cumsum, cumsum!, cumsum_kbn, div, divrem, eigfact, eigfact!, eigmin, eps, erf, erfc, erfcinv, erfcx, erfi, erfinv, exp, exp10, exp2, expm1, exponent, factor, factorial, factorize, floor, gcd, invmod, log, log10, log1p, log2, logspace, max, min, mod, mod1, modf, next, nextpow, nextprod, num, primes, primesmask, prod, realmin, sqrt, sum!, sumabs, sumabs!, sumabs2, sumabs2!,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.