I frequently use MathJax, and often I need to write matrices. Since writing matrices using MathJax is very tiresome task, I decided to automate it.
Code:
import numpy as np
import pyperclip
class Conversion():
def __init__(self, matrix, n = None, m = None):
if matrix == None:
self.matrix = np.random.randint(-10,10, size = [n,m])
else:
'''If variable "matrix", for example, contains [1,2,3,4], instead of [[1,2,3,4]], functions below
will throw error, hence we need to make sure that the data type is correct.'''
if type(matrix[0]) in (str,int,float):
self.matrix = np.array([matrix,])
else:
self.matrix = np.array(matrix)
self.rows = len(self.matrix)
self.cols = len(self.matrix[0])
def single(self, choosen_brackets = ')'):
available_brackets = {' ' : 'matrix',
')' : 'pmatrix',
']' : 'bmatrix',
'}' : 'Bmatrix',
'|' : 'vmatrix',
'||': 'Vmatrix' }
choosen_brackets = available_brackets[choosen_brackets]
body = '$$\\begin {} \n'.format('{' + choosen_brackets + '}')
for row in self.matrix:
row = [str(x) for x in row]
body += ' & '.join(row) + '\\\\' + '\n'
body +='\end {} $$'.format('{' + choosen_brackets + '}')
print(body)
pyperclip.copy(body)
def augmented(self, choosen_brackets = '[]'):
'''We are assuming that the last column of the given matrix is a vector.'''
pos_of_the_verticar_bar = '{' + 'c'*(self.cols-1) + '|' + 'c' + '}'
body = '$$\\left [ \\begin {array} %s \n' % (pos_of_the_verticar_bar)
for row in self.matrix:
row = [str(x) for x in row]
body += ' & '.join(row) + '\\\\' + '\n'
body +='\end {array} \\right ]$$'
print(body)
pyperclip.copy(body)
Notes:
Since function
augmented
is quite similar tosingle
, I could've merged them into one. However, I think that keeping them separate makes the code a little bit more readable.On MSE, mathjax equations are enclosed with
$$
instead of\$
"
single
" is a bad name for a function, I admit. I haven't found any better options. Feel free to offer suggestions.
What can be improved?
Written for Python 3.6.5.