首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >合并两个矩阵..。LISP

合并两个矩阵..。LISP
EN

Stack Overflow用户
提问于 2010-05-26 22:55:18
回答 2查看 301关注 0票数 2
代码语言:javascript
复制
(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))))

(合并矩阵'((3 1) (1 3))“((4 2) (1 1))

*- EVAL:变量NULL没有值

我收到了这样一个错误--如何解决这个问题,谢谢

EN

回答 2

Stack Overflow用户

发布于 2011-07-02 12:17:06

OP的密码对我有用。然而,我有动力去改进它,我实现了同样的想法(但是更强大一些)。

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

注意,由于声明,我的代码应该是超级高效的。

代码语言:javascript
复制
(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
EN

Stack Overflow用户

发布于 2011-01-28 22:55:17

您得到的错误消息表明lisp试图将您对null的一个调用作为变量来处理。例如,我可以像Frank那样定义matrix-rows并删除((null matrix-1) (copy-tree matrix-2))表达式周围的括号,从而复制这种行为。我建议您手动检查括号,或者使用类似于黏液的方法,这在我试图编译函数时给了我一个警告。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2917437

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档