Search code examples
pythonarraysmatrixellipsis

slice 2X2 matrix out of 4X4 matrix in python?


I am reading about the use of Ellipsis introduced in Python 3.

Consider this matrix:

A=[
   [1,2,3,4],
   [5,6,7,8],
   [9,10,11,12],
   [13,14,15,16]
  ]

I want to extract various 2 X 2 matrix out of this, preferably using slice notation if possible:

eg:

Top left corner:

B=[
  [1,2],
  [3,4]
  ]

bottom right corner:

c=[
  [[9,10],
   [13,14]
  ]

Middle 2 X 2:

 d=[
    [6,7],
    [10,11]
    ]

I want to try this without using iteration if possible. is Ellipsis helpful in breaking out this higher order array?

I tried the following:

>>> a[:2][:2]
[[1, 2, 3, 4], [5, 6, 7, 8]]
>>> a[:2][:2][:2]
[[1, 2, 3, 4], [5, 6, 7, 8]]
>>> 

somehow last two calls return the same sub-matrix which is not what I looked for


Solution

  • You probably want list comprehensions...

    Top left:

    [x[:2] for x in a[:2]]
    

    Top right:

    [x[2:] for x in a[:2]]
    

    Middle:

    [x[1:3] for x in a[1:3]] or [x[1:3] for x in a[2:4]]
    

    Essentially what you want to be doing is slicing out rows that you don't want (that's what x in a[k:l] is doing) and then slicing out columns with x[m:n].