Tx · LaTeX & TikZ

How to Convert MATLAB Arrays to LaTeX Matrices

Published By the 9to5Science editorial team

At a glance

  1. 1. Choose a format

    Decide how many decimal places to show, such as two places or significant digits.

  2. 2. Format each row

    Print array entries with the chosen numeric format, separating columns with ampersands.

  3. 3. Join the rows

    Separate rows with LaTeX row breaks and wrap them in a matrix environment.

  4. 4. Paste and compile

    Copy the generated text into a LaTeX math environment and compile with amsmath loaded.

MATLAB displays arrays in a layout that is readable in the command window, but that display is not LaTeX source. To use an array in a paper or report, generate a matrix environment: LaTeX uses & between columns and \\ to end a row.

The function below converts a nonempty real numeric array into a bmatrix. It formats entries to six significant digits by default; you can supply another MATLAB numeric format when you call it.

A reusable MATLAB function

Save this code in a file named matrix2latex.m:

function s = matrix2latex(A, fmt)
% Convert a nonempty real numeric array to a LaTeX bmatrix.

    if nargin < 2
        fmt = '%.6g';
    end

    if ~isnumeric(A) || ~ismatrix(A) || isempty(A) || ~isreal(A)
        error('A must be a nonempty, real numeric array.');
    end

    [m, n] = size(A);
    rows = cell(m, 1);

    for i = 1:m
        entries = cell(1, n);
        for j = 1:n
            entries{j} = sprintf(fmt, A(i, j));
        end
        rows{i} = strjoin(entries, ' & ');
    end

    slash = char(92);
    rowBreak = [slash slash sprintf('\n')];
    s = [slash 'begin{bmatrix}' sprintf('\n') ...
         strjoin(rows, rowBreak) sprintf('\n') ...
         slash 'end{bmatrix}'];
end

The function visits entries by row, formats each value with sprintf, and joins columns with &. It joins the finished rows with two backslashes and a newline, then adds the bmatrix opening and closing commands. Using char(92) constructs a literal backslash without having to manage backslash escaping in the MATLAB string.

Worked example

Run the function on a small array:

A = [1.25 2; -3 4.56789];
tex = matrix2latex(A, '%.2f');
disp(tex)

The generated text is:

\begin{bmatrix}
1.25 & 2.00 \\
-3.00 & 4.57
\end{bmatrix}

Here, %.2f prints every value with exactly two digits after the decimal point. The default %.6g instead uses up to six significant digits and omits unnecessary trailing zeros. Other common choices include %.3f for three decimal places and %.4g for four significant digits.

Paste the result into a LaTeX document like this:

\documentclass{article}
\usepackage{amsmath}

\begin{document}

\[
\begin{bmatrix}
1.25 & 2.00 \\
-3.00 & 4.57
\end{bmatrix}
\]

\end{document}

The amsmath package provides the bmatrix environment, which displays square brackets around the entries. Use pmatrix for parentheses or vmatrix for vertical bars. To change the function’s environment, replace both occurrences of bmatrix in its final assignment with the environment you want.

Vectors and other MATLAB values

A row vector becomes a one-row matrix, while a column vector becomes a one-column matrix. For example, matrix2latex([3; 5; 8]) generates three rows with one entry each. This is valid LaTeX, although for a simple vector you might prefer to write the entries directly in the document.

The example handles real numeric arrays. Complex numbers need a formatting rule that chooses how to display real and imaginary parts; the function rejects them rather than producing ambiguous output. Likewise, special values such as NaN and Inf may need custom formatting to look right in mathematical typesetting. For symbolic expressions, MATLAB’s Symbolic Math Toolbox offers latex for converting symbolic objects, though its output format can differ from this function’s bmatrix output.

Common mistakes

  • Using MATLAB’s display as LaTeX. Brackets, spaces, and line breaks shown in the command window are not necessarily valid matrix syntax. Generate & separators and \\ row breaks.
  • Forgetting math mode. Matrix environments belong inside a math environment such as \[ ... \] or \begin{equation} ... \end{equation}.
  • Using an undefined matrix environment. Load amsmath for environments such as bmatrix and pmatrix.
  • Choosing the wrong precision. %.2f rounds to two decimal places; %.2g keeps two significant digits. Use the format that matches how you want values reported.

References

  1. MATLAB Documentation: sprintf
  2. MATLAB Documentation: strjoin
  3. The amsmath package

Spotted an error? Send a correction. Read how we write and check articles in our editorial policy.