两个矩阵的乘法

时间:2017-07-19 04:36:51

标签: list lisp common-lisp list-comprehension

我想问一下如何将两个矩阵相乘。 我有Matrix mat1 '((1 2) (4 5))和mat2 '((3 6) (7 8))。我刚刚实现了这段代码:

(defun multi_matrices (mat1 mat2)
    (cond((or (null mat1) (null mat2)) nil)
         ((not(eq (length mat1) (length mat2))) nil)
         (( format t "~a" (mapcar #'* (car mat1) (car mat2))))
         ((cdr mat1)(multi_matrices (cdr mat1) (cdr mat2)) (print 'OK))))

但我明白了:

(multi_matrices '((1 2) (4 5)) '((3 6) (7 8)))

               (3 12)(28 40)

那部分没问题,但后来我不知道如何对乘法需求等元素求和:此链接显示 how to multiply matrices

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

试试这个:

CL-USER> (defun mmat (mat1 mat2)
           "multiply two matrices as lists of lists"
           (loop with num-rows1 = (length mat1)
              for row1 in mat1
              collect (loop for c from 0 below num-rows1
                         collect (loop for e in row1
                                    for r from 0
                                    sum (* e (nth c (nth r mat2)))))))
MMAT
CL-USER> (mmat '((1 2 3)(4 5 6)) '((7 8)(9 10)(11 12)))
((58 64) (139 154))

该功能不会检查输入是否正确。