Home > Enterprise >  What does a 3-parameter index of a matrix refer to? (Python)
What does a 3-parameter index of a matrix refer to? (Python)

Time:10-11

I am experimenting with NumPy and matrices in python.

If I have an identity_matrix of length 4 (4x4):

[[1, 0, 0, 0]
 [0, 1, 0, 0]
 [0, 0, 1, 0]
 [0, 0, 0, 1]]

I know that identity_matrix[0] will output the first row, and identity_matrix[0,1] would output the second element of the first vector of the matrix.

Now what does the indexing identity_matrix[[2,2,0]] refer to? Please tell me what each index number represents. Also, why with the double square brackets? The output of this results in the following matrix:

[[0. 0. 1. 0.]
 [0. 0. 1. 0.]
 [1. 0. 0. 0.]]

CodePudding user response:

Answer:

What you are creating is a new array, which consists of the "rows" of your identiy matrix. I.e.:

identity_matrix[[2,2,0]] equals to a new array of lenght 3 (as [2,2,0] has length 3) with two times the row indexed by 2 (i.e. row 3) and one time the row indexed by 0 (i.e. row 1).

Hence, you get:

    [[0. 0. 1. 0.] (row 3 of identity matrix ,i.e. identity_matrix[2])
     [0. 0. 1. 0.] (row 3 of identity matrix, identity_matrix[2])
     [1. 0. 0. 0.]] (row 1 of identity matrix, identity_matrix[0])

Reference:

https://numpy.org/devdocs/user/basics.indexing.html#integer-array-indexing

CodePudding user response:

identity_matrix[row_number] will you single row vector, if you want to get multiple rows using single line statement, you can do identity_matrix[[first_row_index, second_row_index, ...]]

  • Related