; your code goes here
(deftemplate matrix (slot data))
;; === Множення двох матриць ===
(deffunction mat-mul (?m1 ?m2)
(bind ?result (create$))
(bind ?rows (length ?m1))
(bind ?cols (length (nth$ 1 ?m2)))
(bind ?inner (length (nth$ 1 ?m1)))
(foreach ?row ?m1
(bind ?new-row (create$))
(for (?j 1 ?cols)
(bind ?sum 0)
(for (?k 1 ?inner)
(bind ?sum (+ ?sum (* (nth$ ?k ?row) (nth$ ?k (nth$ ?j (transpose ?m2))))))
)
(bind ?new-row (create$ ?new-row ?sum))
)
(bind ?result (create$ ?result ?new-row))
)
?result
)
;; === Транспонування матриці ===
(deffunction transpose (?matrix)
(bind ?rows (length ?matrix))
(bind ?cols (length (nth$ 1 ?matrix)))
(bind ?result (create$))
(for (?j 1 ?cols)
(bind ?new-row (create$))
(for (?i 1 ?rows)
(bind ?new-row (create$ ?new-row (nth$ ?j (nth$ ?i ?matrix))))
)
(bind ?result (create$ ?result ?new-row))
)
?result
)
;; === Піднесення матриці до степеня ===
(deffunction mat-pow (?matrix ?power)
(bind ?result ?matrix)
(if (= ?power 1) then
(return ?result)
)
(for (?i 2 ?power)
(bind ?result (mat-mul ?result ?matrix))
)
?result
)
;; === Допоміжна функція — копіювання матриці ===
(deffunction copy-matrix (?matrix)
(bind ?result (create$))
(foreach ?row ?matrix
(bind ?result (create$ ?result (create$ ?row)))
)
?result
)
;; === Інверсія матриці методом Гаусса-Жордана ===
(deffunction mat-inverse (?matrix)
(bind ?n (length ?matrix))
(bind ?aug (create$))
(for (?i 1 ?n)
(bind ?row (nth$ ?i ?matrix))
(bind ?identity (create$))
(for (?j 1 ?n)
(if (= ?i ?j) then
(bind ?identity (create$ ?identity 1))
else
(bind ?identity (create$ ?identity 0))
)
)
(bind ?aug (create$ ?aug (create$ ?row ?identity)))
)
;; Прямий хід
(for (?i 1 ?n)
(bind ?pivot (nth$ ?i (nth$ ?i ?aug)))
(if (= ?pivot 0) then (return FALSE))
;; нормалізація
(for (?j 1 (* 2 ?n))
(bind ?val (/ (nth$ ?j (nth$ ?i ?aug)) ?pivot))
(modify ?aug (replace$ ?i ?i (replace$ (nth$ ?i ?aug) ?j ?j ?val)))
)
;; занулення інших
(for (?k 1 ?n)
(if (<> ?k ?i) then
(bind ?factor (nth$ ?i (nth$ ?k ?aug)))
(for (?j 1 (* 2 ?n))
(bind ?val (- (nth$ ?j (nth$ ?k ?aug)) (* ?factor (nth$ ?j (nth$ ?i ?aug)))))
(modify ?aug (replace$ ?k ?k (replace$ (nth$ ?k ?aug) ?j ?j ?val)))
)
)
)
)
;; Витяг інвертованої частини
(bind ?inverse (create$))
(for (?i 1 ?n)
(bind ?row (subseq$ (+ ?n 1) (* 2 ?n) (nth$ ?i ?aug)))
(bind ?inverse (create$ ?inverse ?row))
)
?inverse
)
;; === Головна функція ===
(defrule compute-matrix-expression
=>
(bind ?A ((create$ (create$ 5 3 1 8)
(create$ 2 1 4 2)
(create$ 7 6 4 3)
(create$ 9 3 5 1))))
(bind ?B ((create$ 9 7 1 8)
(create$ 2 4 6 1)
(create$ 7 5 3 9)
(create$ 4 6 8 7)))
(bind ?C ((create$ 12 3 2 5)
(create$ 1 10 4 2)
(create$ 3 6 9 3)
(create$ 7 3 5 8)))
(bind ?B3 (mat-pow ?B 3))
(bind ?prod1 (mat-mul ?A ?B3))
(bind ?prod2 (mat-mul ?prod1 ?C))
(bind ?inverse (mat-inverse ?prod2))
(printout t "Inverse matrix: " crlf)
(foreach ?row ?inverse
(printout t ?row crlf)
)
)
(exit)
; empty line at the end