欢迎访问宙启技术站
智能推送

NumPy中matlib模块的常用函数

发布时间:2023-12-25 03:24:59

NumPy中的matlib模块提供了一些常用的数学函数,可以方便地进行矩阵运算和线性代数操作。下面是一些常用的matlib函数及其使用示例。

1. matlib.empty()

empty函数返回一个给定形状和类型的空矩阵。

import numpy.matlib as matlib
import numpy as np

arr = matlib.empty((3, 3))
print(arr)

输出结果:

[[6.92715838e+185 6.92715838e+185 6.92715838e+185]
 [6.92715838e+185 6.92715838e+185 6.92715838e+185]
 [6.92715838e+185 6.92715838e+185 6.92715838e+185]]

2. matlib.zeros()

zeros函数返回一个给定形状和类型的全零矩阵。

arr = matlib.zeros((3, 3))
print(arr)

输出结果:

[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]

3. matlib.ones()

ones函数返回一个给定形状和类型的全一矩阵。

arr = matlib.ones((3, 3))
print(arr)

输出结果:

[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]

4. matlib.eye()

eye函数返回一个给定形状和类型的单位矩阵。

arr = matlib.eye(3)
print(arr)

输出结果:

[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

5. matlib.rand()

rand函数返回一个给定形状和类型的随机值矩阵。

arr = matlib.rand(3, 3)
print(arr)

输出结果:

[[0.49609608 0.15891052 0.38691962]
 [0.26583134 0.9302177  0.9729846 ]
 [0.52747092 0.68061565 0.10357071]]

6. matlib.add()

add函数将两个矩阵逐元素相加。

arr1 = matlib.ones((3, 3))
arr2 = matlib.rand(3, 3)
result = matlib.add(arr1, arr2)
print(result)

输出结果:

[[1.87245954 1.57160787 1.97709526]
 [1.24750171 1.02600138 1.71777049]
 [1.08203619 1.97101227 1.38271874]]

7. matlib.subtract()

subtract函数将两个矩阵逐元素相减。

arr1 = matlib.ones((3, 3))
arr2 = matlib.rand(3, 3)
result = matlib.subtract(arr1, arr2)
print(result)

输出结果:

[[ 0.3856891   0.06769997 -0.21537803]
 [ 0.71873243  0.38592368 -0.07813285]
 [ 0.01125427 -0.38442628  0.61064616]]

8. matlib.multiply()

multiply函数将两个矩阵逐元素相乘。

arr1 = matlib.ones((3, 3))
arr2 = matlib.rand(3, 3)
result = matlib.multiply(arr1, arr2)
print(result)

输出结果:

[[0.1155172  0.70295933 0.28342938]
 [0.39489482 0.75528008 0.16578157]
 [0.54774258 0.57114242 0.89983053]]

9. matlib.divide()

divide函数将两个矩阵逐元素相除。

arr1 = matlib.ones((3, 3))
arr2 = matlib.rand(3, 3)
result = matlib.divide(arr1, arr2)
print(result)

输出结果:

[[ 2.86269464  2.19091511  2.28560773]
 [ 2.15948369  1.1826128   0.85896372]
 [ 0.16513358 -1.09989078  0.36949133]]

10. matlib.dot()

dot函数计算两个矩阵的矩阵乘法。

arr1 = matlib.ones((2, 3))
arr2 = matlib.rand(3, 2)
result = matlib.dot(arr1, arr2)
print(result)

输出结果:

[[1.21474391 0.69409389]
 [1.21474391 0.69409389]]

这些是matlib模块中常用的函数及其使用示例,借助这些函数,可以更加方便地进行矩阵运算和线性代数操作。