0

Let

X = [[2,3, 5, 6], 
     [4,5, 9, 10], 
     [6,1, 3, 9], 
     [3,7, 11, 12]]

How do I output the sub-matrices such that X = [ [A, B], [C, D]]?

    A = [[2, 3], 
         [4,5]]
    B = [[5,6], 
        [9, 10]] 
    C = [[6, 1], 
         [3,7]]
    D = [[3,9], 
        [11, 12]] 
Ryan J. Shrott
  • 592
  • 1
  • 8
  • 26

6 Answers6

2

Without numpy you can do it like this....

X = [[2,3, 5, 6], 
         [4,5, 9, 10], 
         [6,1, 3, 9], 
         [3,7, 11, 12]]

for i in X:
   print([i[ :len(i)//2],i[len(i)//2:]])
Vadim
  • 4,219
  • 1
  • 29
  • 44
2

You can try this, assuming the X is always a 4X4 Matrix:

X = [[2,3, 5, 6], 
 [4,5, 9, 10], 
 [6,1, 3, 9], 
 [3,7, 11, 12]]

new_matrix = [[X[i][:2], X[i+1][:2]] for i in range(0, len(X), 2)]
new_matrix.extend([[X[i][2:], X[i+1][2:]] for i in range(0, len(X), 2)]) 
print(new_matrix)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

A solution using Numpy would look like this:

A = X[0:2, 0:2]
B = X[0:2, 2:4]
C = X[2:4, 0:2]
D = X[2:4, 2:4]
Antimony
  • 2,230
  • 3
  • 28
  • 38
1

For the first sub-matrix you can use

A = [row[:2] for row in X[:2]]

(and similarly for the others)

user2314737
  • 27,088
  • 20
  • 102
  • 114
1

Here is a solution without using numpy.

A = [X[i][:2] for i in range(2)]
B = [X[i][2:] for i in range(2)]
C = [X[i][:2] for i in range(2,4)]
D = [X[i][2:] for i in range(2,4)]

>>> A
[[2, 3], [4, 5]]
>>> B
[[5, 6], [9, 10]]
>>> C
[[6, 1], [3, 7]]
>>> D
[[3, 9], [11, 12]]
1

One liner version, though its a bit less readable

>>> (A,B),(C,D)= [([X[i][:2],X[i+1][:2]],[X[i][2:],X[i+1][2:]]) for i in range(0,len(X),2)]
>>>
>>? A
[[2, 3], [4, 5]]
>>? B
[[5, 6], [9, 10]]
>>? C
[[6, 1], [3, 7]]
>>? D
[[3, 9], [11, 12]]
>>?
Skycc
  • 3,496
  • 1
  • 12
  • 18