How to Implement Matrix Manipulation in Python


1.  Introduction

In this example, we will learn the method to create a matrix and implement basic matrix manipulation in Python.

2. Create A Matrix

We can create a multi-dimensional array, which can also be viewed as a matrix.:

import numpy as np
# Create 1*3 dimensional matrix
a = np.array([1, 2, 3], dtype=int)
print(a)

# Print dimension information
print(a.shape)
print(a.size)
print(a.itemsize)

# Create 2*3 dimensional matrix
b=np.array([[1,2,3],[4,5,6]],dtype=int)
print(b)

# Dimension information
print(b.shape)
print(b.size)
print(b.itemsize)

Output:

[1 2 3]
(3,)
3
4
[[1 2 3]
 [4 5 6]]
(2, 3)
6
4

We can use mat() function to create a matrix.

import numpy as np
print('One matrix:')
# Create a 2*3 zero matrix
data1 = np.mat(np.zeros((3,2),dtype=int))
print(data1)

print('Another matrix:')
# Create a 2*3 integer 1 matrix. The default is floating point data. If you need an int type, you can use dtype=int.
data2=np.mat(np.ones((2,3),dtype=int))
print(data2)

Output:

One matrix:
[[0 0]
 [0 0]
 [0 0]]
Another matrix:
[[1 1 1]
 [1 1 1]]

3. Multiply Matrix

import numpy as np

data1 = np.mat(np.ones((3,3),dtype=int))
data2=np.mat(np.ones((3,3),dtype=int))
print('Matrix multiplication:')
data3=data1*data2
print(data3)

print('Element-wise matrix multiplication')
data4=np.multiply(data1,data2)
print(data4)

Output:

Matrix multiplication:
[[3 3 3]
 [3 3 3]
 [3 3 3]]
Element-wise matrix multiplication
[[1 1 1]
 [1 1 1]
 [1 1 1]]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement