Knowledge Base

Matrices and Matrix Operations

Glossary

A matrix — a rectangular numeric table or two-dimensional array consisting of m rows and n columns

A transpose of the matrix — a matrix operation when its rows become columns with the same numbers

Practice

1# A matrix from a list of lists
2
3import numpy as np
4
5matrix = np.array([
6 [1, 2, 3],
7 [4, 5, 6],
8 [7, 8, 9]])
9print(matrix)

1# A matrix from a list of vectors
2
3import numpy as np
4
5string0 = np.array([1,2,3])
6string1 = np.array([-1,-2,-3])
7list_of_vectors = [string0, string1]
8matrix_from_vectors = np.array(list_of_vectors)
9
10print(matrix_from_vectors)

1# A matrix from data frames
2
3import pandas as pd
4import numpy as np
5
6matrix = df.values
7print(matrix)
8
9# matrix dimensions
10print('Size:', matrix.shape)
11# vector is the second row of the matrix
12print('Row 2:', matrix[2, :])
13# vector is the first row of the matrix
14print('Column 1:', matrix[:, 1])

1# Matrix by vector multiplication
2
3import numpy as np
4
5A = np.array([
6 [1, 2, 3],
7 [4, 5, 6]])
8
9b = np.array([7, 8, 9])
10
11print(np.dot(A, b))
12print(A.dot(b))

1# Matrix by matrix multiplication
2
3import numpy as np
4
5print(A.dot(B))
6print(np.dot(A,B))
7print(A @ B)

1# Transpose of matrix
2
3print(matrix.T)

1# Creating a class
2
3class ClassName:
4 def fit(self, arg1, arg2, ...): # class method
5 # method content
Send Feedback
close
  • Bug
  • Improvement
  • Feature
Send Feedback
,