Skip to content

Add mpow function #61

Open
Open

Description

@genmeblog

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 integers

Activity

  1. genmeblog commented on Jan 30, 2026

    @genmeblog
    ContributorAuthor

    As above works only for positive integers it's possible to make fractional power for non-singular matrices for which eigendecomposition exists $A = V D V^{-1}$, then $A^p = V D^p V^{-1}$, where $D^p$ contains a power of diagonal elements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions