Python与矩阵
2020-01-22 本文已影响0人
louyang
image.png
Python与C++编程中的矩阵,都是向上图这样坐标的。行表示为i,列表示为j。例如,上图中 matrix[1][0] 的值为 4。
先用python描述一下这个矩阵:
>>> import numpy
>>> m=numpy.array([[1,2,3],[4,5,6],[7,8,9]])
>>> m
array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])
>>>
1 某一点
>>> m[1,0]
4
2 某一行
>>> m[1]
array([4, 5, 6])
3 某一列
>>> m[:,1]
array([2, 5, 8])
4 切小块
>>> m[1:,1:]
array([[5, 6],
[8, 9]])
5 横遍历
>>> for cell in m.flatten():
... print(cell, end=' ')
...
1 2 3 4 5 6 7 8 9 >>>
>>> for cell in numpy.nditer(m, order='C'):
... print(cell, end=' ')
...
1 2 3 4 5 6 7 8 9 >>>
6 竖遍历
>>> for cell in m.T.flatten():
... print(cell, end=' ')
...
1 4 7 2 5 8 3 6 9 >>>
>>> for cell in numpy.nditer(m, order='F'):
... print(cell, end=' ')
...
1 4 7 2 5 8 3 6 9 >>>
7 3x2 变 2x3 矩阵
>>> m=numpy.array([[1,2],[3,4],[5,6]])
>>> m
array([[1, 2],
[3, 4],
[5, 6]])
>>> m.reshape(2,3)
array([[1, 2, 3],
[4, 5, 6]])
参考
https://www.pythoninformer.com/python-libraries/numpy/index-and-slice/
https://www.pluralsight.com/guides/numpy-arrays-iterating