Back to Over

Iterators · Over · Practice Question

Sum the Rows and Columns of a Matrix

Sign in to track your progress

Question

Given:

m:4 cut 1+til 16
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16

Compute the sum of each row, and separately the sum of each column.

Expected result (rows):

10 26 42 58

Expected result (columns):

28 32 36 40

Solution

sum each m   / row sums
sum m        / column sums

Alternative Solution

+/'[m]   / row sums
+/[m]    / column sums

Explanation

sum each m applies sum independently (each) to every row of m, collapsing each row down to a single number — the row sums. +/'[m] reaches the same result by applying over (+/) to each row instead of the built-in sum.

sum m (and equivalently +/[m]) is different: rather than running over each row independently, plain + between two lists adds them elementwise. Folding + over the whole list of rows with over (/) therefore adds corresponding positions across all four rows together — row 0 + row 1 + row 2 + row 3, position by position — which gives the column sums.

This pair makes the each-vs-over distinction concrete: each treats every row as its own independent unit, while over accumulates across the rows as a whole, which here happens to land on the columns.