简体   繁体   中英

How can I select a small matrix from a larger matrix by its index

I have a larger 2 dimensional matrix which is 36*72 and I want to select a small matrix from it by using indexes.

The matrix looks like this:

[ [312, 113, 525, 543, ...] , 
  [...],
  [...],
   ... ].

And I print the shape like this:

print(array(matrix).shape)
(36, 72)

But when I try to print out the small matrix like this

print(matrix[6:9][9])

The error is "IndexError: list index out of range"

Then I tried

print(matrix[6:9,9])

It showed "TypeError: list indices must be integers, not tuple"

Then I tried

print(matrix[6:9][8:9])

I get the empty list. But when I tried

print(matrix[9][9])

It did give out some number.

With numpy arrays, you can use quite convenient indexing methods, which is a feature of numpy parts of which are refered to as fancy indexing .
Let's try that with a small example 2D-array:

import numpy as np
a=np.arange(48).reshape(6, 8)
print(a)
#[[ 0  1  2  3  4  5  6  7]
# [ 8  9 10 11 12 13 14 15]                                  
# [16 17 18 19 20 21 22 23]                                 
# [24 25 26 27 28 29 30 31]                                
# [32 33 34 35 36 37 38 39]                                 
# [40 41 42 43 44 45 46 47]]             

If you now want to index eg rows 2 and 3 and columns 3 to 6, you can simply write that down in slices, no matter if by constants or variables:

r1 = 2; r2 = 4
print(a[r1:r2, 3:7])
#[[19 20 21 22]                                               
# [27 28 29 30]]            

You might want to read further here: https://docs.scipy.org/doc/numpy/user/basics.indexing.html

Here's an example. I have a 3x3 matrix, named 'a' and I want to select the top left 2x2 matrix named 'c'.

>>> import numpy as np # importing numpy
>>> a=np.matrix('1 2 3;4 5 6;7 8 9') # creating an example matrix, named a
>>> a
matrix([[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]])
>>> b=[[a.item(0,0),a.item(0,1)],[a.item(1,0),a.item(1,1)]] # creating a list, with 1,1 1,2 2,1 and 2,2 indices of a. remember, in math indexing starts from 1 but in most programming languages, it starts from 0
>>> b
[[1, 2], [4, 5]]
>>> c=np.matrix(b) # creating an numpy matrix object from b which is a part of a
>>> c
matrix([[1, 2],
        [4, 5]])
noe =  Mx1[2:4, 2:4 ] # this is the salshuen, but yo use 2 becuse 0 is 1 like bit.
    # Mx1 [row:colems , Colems:row ] |bns be cerefel 
# It confusing but works

noe =[[ 8750.  8750.]
 [ 8750. 70000.]]

Mx1 = [[ 8750.  8750. -8750. -8750.]
 [ 8750.  8750. -8750. -8750.]

 [-8750. -8750.  8750.  8750.]
 [-8750. -8750.  8750. 70000.]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM