Matlab matrix to LaTeX

September 30th, 2007

Here’s a handy Ruby one-liner for converting Matlab output with matrices to a form that can be directly pasted into a LaTeX array.

ruby -ne 'puts($_.strip.split(/\s+/).join(" & ") + " \\\\")'

An example:

matlab -r "[1 2 3; 3 5 7], exit" -nosplash -nodisplay |  ruby -ne 'puts($_.strip.split(/\s+/).join(" & ") + " \\\\")'

outputs

 \\
To & get & started, & type & one & of & these: & helpwin, & helpdesk, & or & demo. \\
For & product & information, & visit & www.mathworks.com. \\
 \\
 \\
A & = \\
 \\
1 & 2 & 3 \\
3 & 5 & 7 \\
 \\
 \\

where the matrix body is ready to be copied directly into a LaTeX array.

A = \left(
  \begin{array}{ccc}
    1 & 2 & 3 \\
    3 & 5 & 7 \\
  \end{array}
  \right)

Sorry, comments are closed for this article.