-
Notifications
You must be signed in to change notification settings - Fork 17
Open
Description
M^n function implemented by mars0i
#data-science > Matrix-vector multiplication in fastmath
(defn mpow
"Multiplies a square matrix by itself n times. n must be a positive
integer or positive floating-point number with no fractional part."
[m n]
(let [[h w] (fmat/shape m)]
(cond
(not= h w)
(print (str "mpow only multiplies square matrices. Matrix shape was [" h " " w "].")) ; throw?
(or (<= n 0)
(not (zero? (rem n 1))))
(print (str "mpow only accepts positive integer powers. Exponent was " n)) ; throw?
:else
(letfn [(either-pow [acc-mat k]
(cond (= k 1) acc-mat
(even? k) (even-pow acc-mat k)
:else (fmat/mulm m (even-pow acc-mat (dec k)))))
(even-pow [acc-mat k]
(let [factor (either-pow acc-mat (/ k 2))]
(fmat/mulm factor factor)))]
(either-pow m (long n)))))) ; allow float integersReactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels
Type
Projects
Status
Backlog