Pymatrix 是一个轻量级矩阵库,支持基本的线性代数运算。矩阵中的元素应该是数字类型以支持基本代数运算 - int、float、有理数、复数。
实例化矩阵
- 使用矩阵构造函数
可以使用 pymatrix 库中 Matrix 类的构造函数来初始化矩阵。
用法:Matrix(rows, cols, fill=val(optional))
参数:
rows - specify number of rows
cols - specify number of columns
fill - initialise all the elements with this value. It is an optional argument, the default fill is 0.
- Example:
Python3
import pymatrix
m = pymatrix.Matrix(2, 3, fill = '2')
print(m)
- Output:
2 2 2 2 2 2
- 使用列表列表
我们可以使用 from_list() 方法将列表列表转换为矩阵,其中每个列表都被视为一行。例子-
Python3
import pymatrix
list = [[1, 2, 3], [6, 4, 7], [3, 9, 1]]
m = pymatrix.Matrix.from_list(list)
print(m)
- Output:
1 2 3 6 4 7 3 9 1
- 使用字符串
我们可以使用from_string()方法将字符串转换为矩阵对象。该字符串用三引号括起来,每一行都被视为一行。例子
Python3
import pymatrix
string = '''1 2 3
6 4 7
3 9 1'''
m = pymatrix.Matrix.from_string(string)
print(m)
- Output:
1 2 3 6 4 7 3 9 1
矩阵法
以下是 pymatrix 库中提供的一些方法:
- 身份(n) -创建给定大小的单位矩阵。这将返回 Matrix 类的对象。
- is_square() -检查给定矩阵是否为方阵。这将返回一个布尔值。
- is_invertible() -检查给定矩阵是否可逆。这将返回一个布尔值。
- inv() -如果存在则返回逆矩阵,否则引发MatrixError异常。
- det() -如果是方阵,则返回行列式矩阵,否则引发 MatrixError(‘非方阵没有行列式’) 异常。
- rank() -返回矩阵的秩,rank为整数类型。
- trans() -返回矩阵的转置。
- adjoint() -返回伴随矩阵。
例子:
Python3
# Python program for Matrix methods
from pymatrix import Matrix
# identity matrix of size 2
identity_matrix = Matrix.identity(2)
print('\nIdentity matrix :')
print(identity_matrix)
m = Matrix.from_list([[1,2,1],[2,1,1],[1,1,1]])
print('\nIs a square matrix :')
print(m.is_square())
print('\nIs an invertible matrix :')
print(m.is_invertible())
print('\nInverse :')
print(m.inv())
print('\nDeterminant :')
print(m.det())
print('\nRank :')
print(m.rank())
print('\nTranspose :')
print(m.trans())
print('\nAdjoint :')
print(m.adjoint())
输出:
Identity matrix : 1 0 0 1 Is a square matrix : True Is an invertible matrix : True Inverse : 0.0 1.0 -1.0 1.0 0.0 -1.0 -1.0 -1.0 3.0 Determinant : -1.0 Rank : 3 Transpose : 1 2 1 2 1 1 1 1 1 Adjoint : 0.0 -1.0 1.0 -1.0 0.0 1.0 1.0 1.0 -3.0
相关用法
- Python PyTorch acos()用法及代码示例
- Python PyTorch asin()用法及代码示例
- Python PyTorch atan()用法及代码示例
- Python PyTorch cos()用法及代码示例
- Python PyTorch cosh()用法及代码示例
- Python PyTorch sin()用法及代码示例
- Python PyTorch sinh()用法及代码示例
- Python PyTorch tan()用法及代码示例
- Python PyTorch tanh()用法及代码示例
- Python PyTorch from_numpy()用法及代码示例
- Python Pytorch randn()用法及代码示例
- Python Pytorch permute()用法及代码示例
- Python PyTorch div()用法及代码示例
- Python PyTorch clamp()用法及代码示例
- Python PyTorch ceil()用法及代码示例
- Python PyTorch add()用法及代码示例
- Python PyTorch abs()用法及代码示例
- Python PyTorch exp()用法及代码示例
- Python PyTorch numel()用法及代码示例
- Python PyTorch is_storage()用法及代码示例
- Python PyTorch is_tensor()用法及代码示例
- Python PyTorch trunc()用法及代码示例
- Python PyTorch frac()用法及代码示例
- Python PyTorch log()用法及代码示例
- Python PyTorch fmod()用法及代码示例
注:本文由纯净天空筛选整理自naina024大神的英文原创作品 Pymatrix module in python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。