美文网首页
Python与矩阵

Python与矩阵

作者: louyang | 来源:发表于2020-01-22 11:09 被阅读0次
    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

    相关文章

      网友评论

          本文标题:Python与矩阵

          本文链接:https://www.haomeiwen.com/subject/wgyezctx.html