Reputation: 409
I am going throw the Clojure for Machine Learning book and I dont understand one part of one function.
(defn square-mat
"Creates a square matrix of size n x n whose
elements are all e. Accepts an option argument
for the matrix implementation"
[n e & {:keys [implementation]
:or {implementation :persistent-vector}}]
(let [repeater #(repeat n %)]
(matrix implementation (-> e repeater repeater))))
(defn id-mat
"Creates an identity matrix of n x n size"
[n]
(let [init (square-mat :clatrix n 0)
identity-f (fn [i j n]
(if (= i j) 1 n))]
(cl/map-indexed identity-f init)))
In this second function, I don't understand this part (if ( = i j) than 1 else n). Why else n? n is size
Upvotes: 4
Views: 396
Reputation: 5395
Look at the definition of clatrix/map-indexed
. It takes a function of three arguments (the row index, the column index, and the element in that position), and a matrix.
In the inner function (fn [i j n] (if (= i j) 1 n)
, n
is bound not to the number of the rows in the matrix, but to the value in the position (i, j) - which happens to be always zero because the init
matrix was initialized with zeros.
Looks like the book is using a very confusing notation (since n
is bound to the number of rows in the matrix in the outer function, it would be better to name the third argument of the inner function x
or somehow else), but the function should still work.
Upvotes: 2