Create a matrix out of an array

10,210

Solution 1

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]])

Solution 2

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.

Solution 3

row = int(input("Enter the number of Rows: \n"))
col = int(input("Enter the number of Column: \n"))
print("Enter how many elements you want: \n")
num1 = row * col
print('Enter your elements in array: ')
for i in range(num1):
    n = int(input("Element " + str(i + 1) + " : "))
    num_array1.append(n)
arr = np.array([num_array1])
newarr = arr.reshape(row, col)
print(newarr)
print(type(newarr))

This should help to create matrix type arrays with custom user input

Share:
10,210
AutomEng
Author by

AutomEng

Machine learning PhD student

Updated on June 18, 2022

Comments

  • AutomEng
    AutomEng almost 2 years

    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.