前面介绍过用dnarray来模拟,但mat更符合矩阵,这里的mat与Matlab中的很相似。(mat与matrix等同)

基本操作

>>> m= np.mat([1,2,3])  #创建矩阵
>>> m
matrix([[1, 2, 3]]) >>> m[0] #取一行
matrix([[1, 2, 3]])
>>> m[0,1] #第一行,第2个数据
2
>>> m[0][1] #注意不能像数组那样取值了
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/site-packages/numpy/matrixlib/defmatrix.py", line 305, in __getitem__
out = N.ndarray.__getitem__(self, index)
IndexError: index 1 is out of bounds for axis 0 with size 1 #将Python的列表转换成NumPy的矩阵
>>> list=[1,2,3]
>>> mat(list)
matrix([[1, 2, 3]]) #Numpy dnarray转换成Numpy矩阵
>>> n = np.array([1,2,3])
>>> n
array([1, 2, 3])
>>> np.mat(n)
matrix([[1, 2, 3]]) #排序
>>> m=np.mat([[2,5,1],[4,6,2]]) #创建2行3列矩阵
>>> m
matrix([[2, 5, 1],
[4, 6, 2]])
>>> m.sort() #对每一行进行排序
>>> m
matrix([[1, 2, 5],
[2, 4, 6]]) >>> m.shape #获得矩阵的行列数
(2, 3)
>>> m.shape[0] #获得矩阵的行数
2
>>> m.shape[1] #获得矩阵的列数
3 #索引取值
>>> m[1,:] #取得第一行的所有元素
matrix([[2, 4, 6]])
>>> m[1,0:1] #第一行第0个元素,注意左闭右开
matrix([[2]])
>>> m[1,0:3]
matrix([[2, 4, 6]])
>>> m[1,0:2]
matrix([[2, 4]])

矩阵求逆、行列式

与Numpy array相同,可参考链接

矩阵乘法

矩阵乘,与Numpy dnarray类似,可以使用np.dot()和np.matmul(),除此之外,由于matrix中重载了“*”,因此“*”也能用于矩阵乘。

>>> a = np.mat([[1,2,3], [2,3,4]])
>>> b = np.mat([[1,2], [3,4], [5,6]])
>>> a
matrix([[1, 2, 3],
[2, 3, 4]])
>>> b
matrix([[1, 2],
[3, 4],
[5, 6]])
>>> a * b #方法一
matrix([[22, 28],
[31, 40]])
>>> np.matmul(a, b) #方法二
matrix([[22, 28],
[31, 40]])
>>> np.dot(a, b) #方法三
matrix([[22, 28],
[31, 40]])

点乘,只剩下multiply方法了。

>>> a = np.mat([[1,2], [3,4]])
>>> b = np.mat([[2,2], [3,3]])
>>> np.multiply(a, b)
matrix([[ 2, 4],
[ 9, 12]])

矩阵转置

转置有两种方法:

>>> a
matrix([[1, 2],
[3, 4]])
>>> a.T #方法一,ndarray也行
matrix([[1, 3],
[2, 4]])
>>> np.transpose(a) #方法二
matrix([[1, 3],
[2, 4]])

值得一提的是,matrix中求逆还有一种简便方法(ndarray中不行):

>>> a
matrix([[1, 2],
[3, 4]])
>>> a.I
matrix([[-2. , 1. ],
[ 1.5, -0.5]])

参考链接:

1、https://blog.csdn.net/taoyanqi8932/article/details/52703686

2、https://blog.csdn.net/Asher117/article/details/82934857

3、https://blog.csdn.net/cqk0100/article/details/76221749

最新文章

  1. centos6.7设置非root帐户自动登录
  2. jsonobject 遍历 org.json.JSONObject
  3. memcache详解
  4. 算法系列4《Luhn》
  5. 【BZOJ】【1022】【SHOI2008】小约翰的游戏John
  6. 软件调试之INT 3讲解
  7. Mac下Intellij IDea发布Web项目详解一
  8. 第四章 Linux环境
  9. Linux文件系统与结构
  10. 基于visual Studio2013解决C语言竞赛题之1075大数阶乘
  11. 调用本地摄像头拍照(H5和画布)
  12. JS 中的this指向问题和call、apply、bind的区别
  13. 安装最新nodejs
  14. Flafka: Apache Flume Meets Apache Kafka for Event Processing
  15. 《Java 多线程编程核心技术》- 笔记
  16. 31Spring的一些想法
  17. [C++ Primer Plus] 第6章、分支语句和逻辑运算符(二)课后习题
  18. Aspose.Cells API 中文版文档 下载
  19. Java中的访问权限细谈
  20. 无用之学matplotlib,numpy,pandas

热门文章

  1. MVC4 razor与aspx的区别以及用法
  2. JDBC的初步了解及使用
  3. Git 时光穿梭鸡 管理修改
  4. iOS风格的弹出框(alert,prompt,confirm)
  5. oracle 查看 job 日志
  6. response.setContentType() 作用及参数用法
  7. spring基础概念AOP与动态代理理解
  8. MDX分页查询
  9. 《javascript设计模式》笔记之第九章:组合模式
  10. 记录下这周的mysql调优工作