合并两个矩阵......在LISP中

时间:2010-05-26 22:55:18

标签: lisp

(defun merge-matrix (matrix-1 matrix-2)
    (if (not (or (eql (matrix-rows matrix-1) (matrix-rows matrix-2)) (null matrix-1) (null matrix-2))) (error "Invalid dimensions."))
    (cond
        ((null matrix-1) (copy-tree matrix-2))
        ((null matrix-2) (copy-tree matrix-1))
        (t (let ((result (copy-tree matrix-1)))
                 (dotimes (i (matrix-rows matrix-1))
                     (setf (nth i result) (nconc (nth i result) (nth i matrix-2))))
                 result))))
  
    

(merge-matrix'((3 1)(1 3))'((4 2)(11)))

  

*** - EVAL:变量NULL没有值

我收到的错误就是如何解决问题,谢谢

2 个答案:

答案 0 :(得分:1)

OP的代码适合我。然而,我觉得有动力改善它 我实现了相同的想法(但更强大)。

语义与Matlab的vertcat相同。 该函数将所有参数附加到一个大矩阵中。

请注意,由于声明,我的代码应该非常高效。

(deftype mat ()
  "Non-square matrices. Last index is columns, i.e. row-major order."
  `(simple-array single-float 2))

(defun are-all-elements-typep (type ls)
  (reduce #'(lambda (b x) (and b (typep x type)))
      ls))

(defun are-all-matrix-heights-equalp (ls)
  (let ((first-height (array-dimension (first ls) 0)))
    (reduce #'(lambda (b x) (and b
                (= first-height
                   (array-dimension x 0))))
       ls)))

(defun vertcat (&rest rest)
  (declare (type cons rest))
  (unless (are-all-elements-typep 'mat rest)
    (break "At least one of the arguments isn't a matrix."))
  (unless (are-all-matrix-heights-equalp rest)
    (break "All Matrices must have the same number of rows."))
  (let* ((height (array-dimension (first rest) 0))
     (widths (mapcar #'(lambda (mat) (array-dimension mat 1)) rest))
     (result (make-array (list height
                   (reduce #'+ widths))
                 :element-type 'single-float))
     (current-width 0))
    (dotimes (m (length rest))
      (let ((e (elt rest m)))
    (destructuring-bind (y x) (array-dimensions e)
     (dotimes (j y)
       (dotimes (i x)
         (setf (aref result j (+ current-width i))
           (aref e j i))))
     (incf current-width (elt widths m)))))
    (the mat result)))

#+nil
(let ((a (make-array '(2 3)
             :initial-contents '((1s0 2s0 3s0)
                     (2s0 4s0 5s0))
             :element-type 'single-float))
      (b (make-array '(2 2)
             :initial-contents '((6s0 7s0)
                     (9s0 8s0))
             :element-type 'single-float)))
  (vertcat a b a))
;=> #2A ((1.0 2.0 3.0 6.0 7.0 1.0 2.0 3.0) (2.0 4.0 5.0 9.0 8.0 2.0 4.0 5.0))

答案 1 :(得分:0)

您收到的错误消息表明,lisp正在尝试将您对null的一次调用视为变量。我能够像Frank Shearar那样定义matrix-rows并删除((null matrix-1) (copy-tree matrix-2)) s-expression周围的括号来复制这种行为。我建议您手动或使用类似SLIME的内容检查您的括号,当我尝试编译该函数时,它会给我一个警告。