Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a matrix out of an array

I am trying to construct a matrix object out of an array. The array has a length of 25, and what I'm trying to do is construct a 5x5 matrix out of it. I have used both numpy.asmatrix() and the matrix constructor but both result in a matrix that has a length of 1. So, what's basically happening is all the elements of the array are considered a tuple and inserted into the newly-created matrix. Is there any way around this so I can accomplish what I want?

EDIT: When I wrote "array", I naively meant a vanilla python list and not an actual numpy.array which would make things a lot simpler. A mistake on my part.

like image 400
AutomEng Avatar asked Dec 18 '25 20:12

AutomEng


2 Answers

Think you probably just want .reshape():

In [2]: a = np.arange(25)

In [3]: a
Out[3]:
array([ 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])

In [4]: a.reshape(5,5)
Out[4]:
array([[ 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]])

You can also convert it into an np.matrix after if you need things from that:

In [5]: np.matrix(a.reshape(5,5))
Out[5]:
matrix([[ 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]])

EDIT: If you've got a list to start, it's still not too bad:

In [16]: l = range(25)

In [17]: np.matrix(np.reshape(l, (5,5)))
Out[17]:
matrix([[ 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]])
like image 57
Randy Avatar answered Dec 20 '25 09:12

Randy


You can simply simulate a Matrix by using a 2-dimensional array with 5 spaces in each direction:

>>>Matrix =  [[0 for x in range(5)] for x in range(5)]

And access the elemets via:

>>>Matrix[0][0]=1

To test the output, print it:

>>>Matrix
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

If you need a specific implementation like numpy, please specify your question.

like image 24
Fr3ak1n0ut Avatar answered Dec 20 '25 11:12

Fr3ak1n0ut



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!