Emacs Lisp: Transpose Matrix 🚀

By Xah Lee. Date: . Last updated: .

Emacs lisp function to create a matrix, and transpose matrix.

(defun xah-make-matrix (Row Col Val)
  "Create a matrix of dimensions Row by Col, filled by Val.
The result is lisp vector datatype, each row is also a vector.

URL `http://xahlee.info/emacs/emacs/elisp_transpose.html'
Version 2022-12-29 2022-12-30 2023-02-15"
  (let (($mtx (make-vector Row Val)))
    (dotimes ($j Row)
      (aset $mtx $j (make-vector Col Val)))
    $mtx))
(defun xah-transpose (Matrix)
  "Transpose a Matrix.
The Matrix is assumed to be 2D.
Matrix must be a lisp vector datatype, and row are vectors too.

Example:
(xah-transpose [ [1 2 3] [4 5 6] ] )
return [[1 4] [2 5] [3 6]]

URL `http://xahlee.info/emacs/emacs/elisp_transpose.html'
Version 2022-12-29 2022-12-30 2023-02-15"
  (let (($rowCount (length Matrix))
        ($colCount (length (aref Matrix 0)))
        $mtx )
    (setq $mtx (xah-make-matrix $colCount $rowCount 1))
    (dotimes ($r $rowCount)
      (dotimes ($c $colCount)
        (aset (aref $mtx $c) $r (aref (aref Matrix $r) $c))))
    $mtx
    ))