![]() |
VOOZH | about |
A matrix is a rectangular two-dimensional array of data like numbers, characters, symbols, etc. which we can store in row and column format. We can perform operations on elements by using an index (i,j) where 'i' and 'j' stand for an index of row and column respectively.
In the Python programming language, we can represent them in many formats like LaTeX matrices, Numpy arrays, Python 2D lists, Sympy Matrix, etc. From this, we will be using LaTeX Matrix to convert it into Sympy Matrix without using any in-built functions like latex2sympy2 and sympy because sometimes this won't work properly for some cases like fractions and symbols. In this article, we'll explore how to convert LaTeX matrices into SymPy matrices using Python.
LaTeX has the ability to write matrices in many formats like matrix (Like arrays), pmatrix (Parentheses), bmatrix [Square brackets], Bmatrix {Curly Brackets}, etc. but we will be using normal arrays like a matrix for conversion as given below.
Note: You can also use different formats of matrices by making a few changes in regex and input.
Sympy is a Python library that allows us to perform mathematical operations over matrices, algebraic expressions, trigonometric equations, calculus equations, and many more. Our goal is to convert the LaTeX matrix into a Sympy matrix. Sympy matrices are outputs of converted LaTeX matrix which we discussed in the above section.
Dowload Sympy library: We need to download sympy library to convert our elements into sympy objects. Just head over to your terminal, type following command and hit ENTER.
pip install sympyBelow function converts latex matrix into sympy matrix which take input in string format and give output in sympy matrix.
Output
Matrix([
[ 1, 9**(1/4), (11/2)/5],
[-2/5, -1.8, 2**4],
[ g, -100, i]])Example 1: 3x3 Matrix of Numbers (Integers, decimals, fractions).
Matrix([
[1/2, -8, 5],
[2.3, -9/5, 0],
[ -4, -6.2, 99]])
Example 2: 2x2 Matrix of Integers.
Input:
Output:
Matrix([
[1, 2],
[3, 4]])
Example 3: 3x3 Matrix of alphabets.
Input:
Output:
Matrix([
[a, b, c],
[d, e, f],
[g, h, i]])
O(m*n), where m and n represents rows and columns respectively.
Conversion of LaTeX matrices into Sympy matrices allows us to perform mathematical opeartions on them which we won't be able to do it with LaTeX matrices. With the help of Sympy parse_latex we easily convert python objects into sympy objects and store them in python 2D-list and further convert it into sympy object which gives us sympy matrix.