Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slicing python matrix into quadrants

Suppose I have the following matrix in python:

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

I want to slice it into the following matrices (or quadrants/corners):

[[1,2], [5,6]]

[[3,4], [7,8]]

[[9,10], [13,14]]

[[11,12], [15,16]]

Is this supported with standard slicing operators in python or is it necessary to use an extended library like numpy?

like image 743
mountaineer1980 Avatar asked Dec 26 '22 16:12

mountaineer1980


2 Answers

If you are always working with a 4x4 matrix:

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

top_left =  [a[0][:2], a[1][:2]]
top_right = [a[0][2:], a[1][2:]]
bot_left =  [a[2][:2], a[3][:2]]
bot_right = [a[2][2:], a[3][2:]]

You could also do the same for an arbitrary size matrix:

h = len(a)
w = len(a[1])
top_left =  [a[i][:w // 2] for i in range(h // 2)]
top_right = [a[i][w // 2:] for i in range(h // 2)]
bot_left =  [a[i][:w // 2] for i in range(h // 2, h)]
bot_right = [a[i][w // 2:] for i in range(h // 2, h)]
like image 194
Nathan Villaescusa Avatar answered Jan 09 '23 02:01

Nathan Villaescusa


The question is already answered, but I think this solution is more general. It can also be used numpy.split and list comprehension in the following way:

import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
B = [M for SubA in np.split(A,2, axis = 0) for M in np.split(SubA,2, axis = 1)]

Getting:

>>>[array([[1, 2],[5, 6]]), 
array([[3, 4],[7, 8]]), 
array([[ 9, 10],[13, 14]]),
array([[11, 12],[15, 16]])]

Now if you want to have them assigned into different variables, just:

C1,C2,C3,C4 = B

Have a look to numpy.split doc. Changing the parameter indices_or_sections you can get a higher number of splits.

like image 32
gv12 Avatar answered Jan 09 '23 02:01

gv12