In this tutorial we will learn about Python Matrix. In our previous tutorial we learnt about Python JSON operations.

Python Matrix

To work with Python Matrix, we need to import Python numpy module. If you do not have any idea about numpy module you can read python numpy tutorial. Python matrix is used to do operations regarding matrix, which may be used for scientific purpose, image processing etc.

Create Matrix Python

In this section we will learn how to create a matrix in python.

According to wikipedia, a matrix is a rectangular array of numbers, symbols, or expressions, arranged in rows and columns. So, in the following code we will be initializing various types of matrices.

Generally a matrix is created using numpy.matix() function. We can use numpy.shape to know the dimension of the matrix. See the following python matrix example code.

You will get output like the following image.

python-matrix

Python Matrix Addition

The manual code for matrix addition is complex enough to write! Thanks to numpy module, we can simply use + operator to for matrix addition. So, in the following example code we will see both to write the addition code manually and also by using plus operator.

The output of the python matrix addition code is following.

Python Matrix Multiplication, Inverse Matrix, Matrix Transpose

In the previous section we have discussed about the benefit of Python Matrix that it just makes the task simple for us. Like that, we can simply Multiply two matrix, get the inverse and transposition of a matrix.

As we have seen before that + operator adds two matrix, here we can simply use * operator to multiply matrices.

For matrix multiplication, number of columns in first matrix should be equal to number of rows in second matrix.

We can get the inverse of a matrix by using getI() function. We can use getT() to get the transpose of matrix. Let’s have a look at matrix multiplication example.

As we have used random values. So the elements of the matrix will vary. However the output of the above code is given below for a sample run in my computer.

So, that’s all for python matrix operations. To know more about python matrix, you may read the official documentation.

By admin

Leave a Reply

%d bloggers like this: