21 python numpy matrix operations

21 python numpy matrix operations

numpy matrix library

  • numpy contains a matrix library numpy.matlib, the function in this module returns a matrix, not an ndarray object
  • The elements in the matrix can be numbers, symbols or mathematical formulas
  • Numpy is different from MATLAB. For multidimensional array operations, matrix operations are not used by default. If you want to perform matrix operations on arrays, you can call the corresponding functions of the ndarray object

Matrix generation matrix function

import numpy as np
x=np.matrix([[1,2,3],[4,5,6]])
y=np.matrix([1,2,3,4,5,6])
#x[0,0]返回行下标和列下标都为0的元素和x[0][0]不同
x[0,0]
Out[4]: 1
x[0][0]
Out[3]: matrix([[1, 2, 3]])
  • matlib.empty() function
    numpy.matlib.empty(shape,dtype,order)
    shape: Integer or integer tuple defining the shape of the new matrix
    Dtype: optional, data type
    order: C (row order first) or F (column order) priority)
import numpy.matlib
import numpy as np
np.matlib.empty((2,2))#填充为随机数据
  • matlib.zeros() creates a matrix filled with 0
  • matlib.ones() creates a matrix filled with 1
  • matlib.eye(n,M,k,dtype) creates a single diagonal element of 1. Other positions 0
    where the number of rows of the n matrix, the number of columns of the M matrix, the default is n (that is, the default unit matrix), k diagonal Index, dtype data type
  • matlib.identity() unit matrix
  • matlib.rand() creates a random array of a given size, randomly filled 0-1

Insert picture description here

Common matrix operations

Matrix and two-dimensional array conversion

import numpy.matlib
import numpy as np

i=np.matrix('1,2;3,4')
j=np.asarray(i)
k=np.asmatrix(i)

Matrix transpose

X is a matrix object XT is transposed

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/bj_zhb/article/details/105514435