Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create 3x3 matrices?

I have a 2D list containing these values:

text = [[4, 3, 8, 9, 5, 1, 2, 7, 6], [8, 3, 4, 1, 5, 9, 6, 7, 2], 
[6, 1, 8, 7, 5, 3, 2, 9, 4], [6, 9, 8, 7, 5, 3, 2, 1, 4], 
[6, 1, 8, 7, 5, 3, 2, 1, 4], [6, 1, 3, 2, 9, 4, 8, 7, 5]]

For instance, text[i] should be printed like this:

4 3 8
9 5 1
2 7 6

But my matrix prints this:

   r = 6
   m = []
    for i in range(r):
        m.append([int(x) for x in text[i]])
    for i in m:
        print (i) 
>>
    4 3 8 9 5 1 2 7 6 
    8 3 4 1 5 9 6 7 2
    6 1 8 7 5 3 2 9 4 
    6 9 8 7 5 3 2 1 4 
    6 1 8 7 5 3 2 1 4 
    6 1 3 2 9 4 8 7 5 
like image 757
pk3 Avatar asked Oct 23 '25 20:10

pk3


1 Answers

You can use numpy. First, convert your list into numpy array. Then, take an element and reshape it to 3x3 matrix.

import numpy as np

text = [[4, 3, 8, 9, 5, 1, 2, 7, 6], [8, 3, 4, 1, 5, 9, 6, 7, 2],
[6, 1, 8, 7, 5, 3, 2, 9, 4], [6, 9, 8, 7, 5, 3, 2, 1, 4],
[6, 1, 8, 7, 5, 3, 2, 1, 4], [6, 1, 3, 2, 9, 4, 8, 7, 5]]

text = np.array(text)

print text[0].reshape((3, 3))
print text[1].reshape((3, 3))

Output:

[[4 3 8]
 [9 5 1]
 [2 7 6]]

[[8 3 4]
 [1 5 9]
 [6 7 2]]

With numpy, you are really working with matrices

like image 166
dragon2fly Avatar answered Oct 25 '25 11:10

dragon2fly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!