Lisp 合并两个矩阵。。。口齿不清
(合并矩阵“((31)(13))”((42)(11))) ***-EVAL:变量NULL没有值Lisp 合并两个矩阵。。。口齿不清,lisp,Lisp,(合并矩阵“((31)(13))”((42)(11))) ***-EVAL:变量NULL没有值 我收到了这样一个错误:如何解决问题,谢谢。您收到的错误消息表明lisp试图将您对null的一个调用视为一个变量。例如,我可以像Frank Shearr那样定义矩阵行,并删除((null matrix-1)(copy tree matrix-2))s表达式周围的括号,从而复制这种行为。我建议您手动或使用类似的方法检查括号,这在我试图编译函数时给了我一个警告。OP的代码适合我。然而,我感到有动力去改进它,
我收到了这样一个错误:如何解决问题,谢谢。您收到的错误消息表明lisp试图将您对
null
的一个调用视为一个变量。例如,我可以像Frank Shearr那样定义矩阵行
,并删除((null matrix-1)(copy tree matrix-2))s表达式周围的括号,从而复制这种行为。我建议您手动或使用类似的方法检查括号,这在我试图编译函数时给了我一个警告。OP的代码适合我。然而,我感到有动力去改进它,并且
我实现了同样的想法(但功能更强)
语义与Matlab的vertcat相同。
该函数将所有参数追加到一个大矩阵中
注意,由于声明,我的代码应该是超级高效的
(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))))
矩阵行是什么样子的?例如,如果我使用(defun matrix rows(matrix)(length matrix)),我会得到答案((3 1 4 2)(1 3 1 1))。函数应该做什么?
(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))