What are the three ways for python to generate unit or diagonal matrices
This article introduces the knowledge about "Python generates unit array or diagonal array in three ways". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!
Python generates unit or diagonal matrices
Premise:
import numpy as np1.identitynp.identity(4)array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) 2.eyenp.eye(4)array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) 3.diag (diagonal elements can be specified) np.diag([1] * 4)Out[1]: array([[1, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]])np.diag([2] * 4)Out[2]: array([[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]])
What's interesting is that the first two methods are floating-point numbers, and the last one is integers, so it's good to distinguish them when you use them.
python np.eye() function to create diagonal matrix
Recently, blogger is studying kalman filter, in which the initial matrix definition needs diagonal matrix, so check some data, found that numpy has an eye function can achieve this purpose
np.eye(N,M=None,k=0,dtype=,order='C)
N represents the number of rows output;
M represents the number of columns output, not given by default is equal to N;
K is equal to 0 by default, representing the main diagonal, negative numbers represent the low diagonal, and positive numbers represent the high diagonal;
dtype indicates the type of output data;
Order indicates whether the output array is stored in memory in C row-first 'C' or Fortran column-first 'F' form.
See the following two examples to understand the usage a = np.eye(4) print(type(a)) print(a) a = np.mat(a) print(type(a)) print(a) a = a.I print(type(a)) print(a)>>>[[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] [[1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.]] a = np.eye(4,k=1) print(type(a)) print(a) a = np.mat(a) print(type(a)) print(a) a = a.T print(type(a)) print(a)>>>[[0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.] [0. 0. 0. 0.]] [[0. 1. 0. 0.] [0. 0. 1. 0.] [0. 0. 0. 1.] [0. 0. 0. 0.]] [[0. 0. 0. 0.] [1. 0. 0. 0.] [0. 1. 0. 0.] [0. 0. 1. 0.]] The content of "Python generates unit arrays or diagonal arrays in three ways" is introduced here. Thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!