Emacs: 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 ((xmtx (make-vector Row Val)))
    (dotimes (xj Row)
      (aset xmtx xj (make-vector Col Val)))
    xmtx))
(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 ((xrowCount (length Matrix))
        (xcolCount (length (aref Matrix 0)))
        xmtx )
    (setq xmtx (xah-make-matrix xcolCount xrowCount 1))
    (dotimes (xr xrowCount)
      (dotimes (xc xcolCount)
        (aset (aref xmtx xc) xr (aref (aref Matrix xr) xc))))
    xmtx
    ))

Emacs Lisp, Vector