How to print elements of a matrix in LaTeX formatting?

Given a matrix

A = [[182740835762038560236502360265029360346025236045;;
 2];
[328470287402983460892460286408129634;;
 4]]

I’d like to get LaTeX-formatted output, one element per line, e.g.:

latexprint(A)

A_{1,1} = 182740835762038560236502360265029360346025236045
...
A_{2,2} = 4

Is there a package to do this?

If not, how do I:

  • Substitute the variable name A into a string?
  • Get all the Cartesian indices for the matrix and interpolate the string with them? eachindex() is 1:4 in this case, which is not very convenient.

somthing like

["A_{$i,$j} = $(A[i,j])" for i in 1:size(A,1), for j in 1:size(A,2)]

?

You might take a look at LaTeXStrings.jl

Thanks!

Can I put the variable name here programmatically?

Julia warns one should use eachindex and the like, but I doubt I will ever need to print offset arrays. However, the disadvantage is that I can’t print arbitrary Nd-arrays like this.

For Nd arrays, use CartesianIndices. Look at the docs with ?CartesianIndex or maybe ?CartesianIndices directly.

Not with a function. You do could do it with a macro, e.g. you could write a macro:

macro latexprint(A)
    :(latexprint(A, $(string(A))))
end
function latexprint(A, name)
    for i in CartesianIndices(A)
        println(name, "_{", join(Tuple(i),','), "} = ", A[i])
    end
end

e.g.

julia> A = [1 2; 3 4]
2×2 Matrix{Int64}:
 1  2
 3  4

julia> @latexprint(A)
A_{1,1} = 1
A_{2,1} = 3
A_{1,2} = 2
A_{2,2} = 4
2 Likes