kigubkur.datafun.sum
Sum function
(require '[kigubkur.datafun [sum :refer [sum]]])
Examples
Sum of a vector
This returns the sum of elements.
=> (def r [[1 2 3 4]])
=> (def c [[1][2][3][4]])
=> (view r)
[1 2 3 4]
Order -> 1 x 4
=> (sum r)
10
=> (view c)
[1]
[2]
[3]
[4]
Order -> 4 x 1
=> (sum c)
10
Sum of a matrix
By default this returns a row vector containing the sum of each column.
=> (def M [[1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5]])
=> (view M)
[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]
Order -> 4 x 5
=> (view (sum M))
[4 8 12 16 20]
Order -> 1 x 5
But for sum of each row
=> (sum M "rows")
[[15 15 15 15]]
Sum of a block
(require '[kigubkur.construct [blocking :refer [block]]])
=> (def L [[1 2 3 4 5 6 7 8 9 10]
[1 2 3 4 5 6 7 8 9 10]
[1 2 3 4 5 6 7 8 9 10]
[1 2 3 4 5 6 7 8 9 10]
[1 2 3 4 5 6 7 8 9 10]
[1 2 3 4 5 6 7 8 9 10]
[1 2 3 4 5 6 7 8 9 10]])
=> (def B (block L 5))
=> (pprint B)
[[{:A11 [[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]],
:A12 [[6 7 8 9 10]
[6 7 8 9 10]
[6 7 8 9 10]
[6 7 8 9 10]
[6 7 8 9 10]]}]
[{:A22 [[6 7 8 9 10]
[6 7 8 9 10]],
:A21 [[1 2 3 4 5]
[1 2 3 4 5]]}]]
=> (view (sum B))
[7 14 21 28 35 42 49 56 63 70]
Size -> 1 x 10
=> (sum B "rows")
[[55 55 55 55 55 55 55]]
sum
(sum M & arg)
Sum of all vector elements or of each column or row vector elements in a matrix and returns a scalar or a row-vector.
Syntax | Purpose |
---|---|
(sum x) | sum element; x is a row/column |
(sum x) | row containing sum of each column; x is a matrix/block |
(sum x "rows") | row containing sum of each row; x is a matrix/block |