【Python矩阵及其基础操作】【numpy matrix】

一、矩阵生成

  1、numpy.matrix:

 1 import numpy as np
 2 
 3 x = np.matrix([ [1, 2, 3],[4, 5, 6] ])
 4 y = np.matrix( [1, 2, 3, 4, 5, 6])
 5 
 6 print(x, y, x[0, 0], sep='\n\n')
 7 
 8 matrix([[1, 2, 3]
 9     [4, 5, 6]])
10 
11 [[1 2 3 4 5 6]]
12 
13 1
14 
15 [[1 2 3]]

  2、numpy.matlib.empty( shape, dtype, order)

  • shape:定义新矩阵形状的整数或整数元组
  • dtype:数据类型,可选。
  • order:C(行序优先)或F(列序优先)
import numpy.matlib
import numpy as np

print (np.matlib.empty((2,2)))

#输出一个填充为随机数的2行2列的矩阵

  3、numpy.matlib.zeros()  numpy.matlib.ones()

1 import numpy.matlib
2 import numpy as np
3 
4 print (np.matlib.zeros((2, 2)))    #输出一个全为0的2行2列矩阵
5 print (np.matlib.ones((2, 2)))      #输出一个全为1的2行2列矩阵

  4、numpy.matlib.eye()

    返回一个对角元素为1,其他位置为0的矩阵,当M=n时为单位矩阵。

 1 #numpy.matlib.eye( n, M, k, dtype)
 2 '''n:返回矩阵的行数
 3 M:返回矩阵的列数,默认为n
 4 k:对角线的索引
 5 dtype:数据类型 '''
 6 
 7 import numpy.matlib
 8 import numpy as np
 9 
10 print (np.matlib.eye(n = 3, M = 4, k = 0, dtype = int)
11 
12 [[1 0 0 0]
13 [0 1 0 0]
14 [0 0 1 0]]

  5、numpy.matlib.identity()

    返回给定大小的单位矩阵。单位矩阵是一个方针,其左上角到右下角的对角线上的元素均为1,其余位置全为0。

1 import numpy.matlib
2 import numpy as np
3 
4 print (np.matlib.identity(4, dtype = int))    #输出4*4的单位矩阵

  6、numpy.matlib.rand()

    创建一个给定大小的、数据是随机填充的矩阵。

import numpy.matlib
import numpy as np

print (np.matlib.rand(4, 4))   #输出一个4*4的矩阵

二、矩阵常用操作

  1、矩阵与二维数组相互转换

    矩阵总是二维的,ndarray是一个n维数组,可以用如下代码使其相互转换

1 import numpy.matlib
2 import numpy as np
3 
4 a = np.matrix('1,2;3,4')      #创建一个2*2矩阵a  
5 print(a)                                #输出矩阵a
6 b = np.asarray(a)               #将矩阵a转换为2维数组b
7 print(b)                                #输出数组b
8 c = np.asmatrix(b)             #将数组b转换为矩阵c
9 print(c)                                 #输出矩阵c

代码中的三个print输出的结果均为    [[1 2]

                   [3 4]]

  2、矩阵转置

import numpy as np

a = np.matrix([1, 2],[3, 4]])
print(a.T)          #输出a的转置矩阵

  3、查看矩阵特征

 1 import numpy as np
 2 
 3 x = np.matrix([[1, 2, 3],[4, 5, 6]])
 4 
 5 print(x.mean())                   #输出所有元素平均值
 6 
 7 print(x.mean(axis=0))         #输出纵向平均值
 8 
 9 print(x.mean(axis=1))         #输出横向平均值
10 
11 print(x.sum())                     #输出所有元素之和
12 
13 print(x.max(axis=1))           #输出横向最大值
14 
15 print(x.argmax(axis=1))       #输出横向最大值的下标
16 
17 print(x.diagonal())                #输出对角线元素

  4、矩阵乘法

    矩阵乘法可直接使用*连接两个矩阵

import numpy as np

x = np.matrix([[1, 2, 3],[4, 5, 6]])
y = np.matrix([[1, 2],[3, 4],[5, 6]])
print(x*y)

输出结果为

[[22 28]

[49 64]]

  5、numpy,linalg函数

  1. diag:以一维数组的形式返回方阵的对角线元素,或将一维数组转换为方阵(非对角线元素为0)
  2. dot:矩阵乘法
  3. trace:计算对角线元素的和
  4. det:计算矩阵行列式
  5. eig:计算方阵的特征值和特征向量
  6. inv:计算方阵的逆
  7. svd:计算奇异值分解(SVD)
  8. solve:解线性方程组Ax=b,其中A为一方阵
  9. lstsq:计算Ax=b的最小二乘解
 1 #numpy.dot()演示
 2 import numpy.matlib
 3 import numpy as np
 4 
 5 a = np.array([[1, 2],[3, 4]])
 6 b = np.array([[11, 12],[13, 14]])
 7 
 8 print(np.dot(a,b))
 9 
10 #输出结果为
11 [[37 40]
12 [85 92]]

猜你喜欢

转载自www.cnblogs.com/biqianxiang/p/12311918.html