Skip to content

Instantly share code, notes, and snippets.

@egefeyzioglu
Created November 10, 2023 11:09
Show Gist options
  • Save egefeyzioglu/3bb4f78e457a5a01092df6f2aa5c8ee6 to your computer and use it in GitHub Desktop.
Save egefeyzioglu/3bb4f78e457a5a01092df6f2aa5c8ee6 to your computer and use it in GitHub Desktop.
Julia function to display a given matrix prettily in Markdown/KaTeX, optionally limiting the number of rows/columns shown
using Markdown;
# Displays given matrix R in Markdown using KaTeX
# Optional parameter lims sets how many rows and columns (respectively) will be shown
# \cdots, \vdots, and \ddots are used in place of skipped cells
function dispMatrix(R, lims=[Inf,Inf])
i = -1 # Start at beginIndex - 2 = 1 - 2 = -1. Minus 2 because one taken up by the \vdots, the other taken up by the last element
sizes = size(R)
show = min.(sizes,lims)
str = "\$\$\\begin{bmatrix} "
for row in eachrow(R)
# We want to print the numbers for the first (limit-1) rows and the last row
if(show[1] - 2 > i || sizes[1] == i+2)
if(sizes[2] <= lims[2])
# If we'll show the entire row, just join it together
str *= join(row, " & ")
else
# Otherwise, get the first (limit-1) items and the last item only
str *= join(row[1:show[2]-1], " & ")
str *= " & \\cdots & "
str *= string(row[sizes[2]])
end
str *= " \\\\ "
# For the limit'th row, print the dots
# This can be any row after (limit-1) as long as it happens only once,
# I just arbitrarily picked the one following (limit-1)
elseif(show[1] - 1 == i)
# Again, this needs to behave differently depending on if we're showing the entire row
if(sizes[2] <= lims[2])
# If we are, just show[2] of \vdots in an array and join them with &'s
dots = []
for _ in 1:show[2]
push!(dots, "\\vdots")
end
str *= join(dots, " & ")
else
# Otherwise, we want to first show (limit-1) of \vdots, then \ddots, then \vdots again
dots = []
for _ in 1:show[2]-1
push!(dots, "\\vdots")
end
str *= join(dots, " & ")
str *= " & \\ddots & \\vdots"
end
str *= " \\\\ "
end
i+=1;
end
str *= "\\end{bmatrix}\$\$"
display(Markdown.parse(str))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment