Iterators · Each · Practice Question
Sum the Diagonal of a Matrix
Question
Given:
m:4 cut 1+til 161 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16Sum the diagonal of the matrix.
Expected result:
34Solution
sum m'[til count m;til count m]Alternative Solution
sum m @' til count mAlternative Solution
sum .[m;] each (til 4),'(til 4)Explanation
The diagonal of m is the value at row 0/col 0, row 1/col 1, row 2/col 2, row 3/col 3 — i.e. indexing m at (i;i) for every i from 0 to count m - 1.
m @' til count muses each-both (@') to pair every row index in til count m (0 1 2 3) with itself, indexing m once per row at that row's own position: m[0;0], m[1;1], m[2;2], m[3;3]. each-both is what lets the same index list serve as both the row selector and, paired against itself, the column selector — each row of m only ever gets indexed by its corresponding entry.
sum then adds up the four diagonal values 1 6 11 16, giving 34.
m'[til count m;til count m] and .[m;] each (til 4),'(til 4) reach the same values by different routes — the latter builds explicit (i;i) index pairs first with each-both (,'), then applies . to look each one up, before summing.