Rishav Mitra
Rishav Mitra

Reputation: 21

Making a matrix with numpy.array

I tried to create a matrix using numpy.array with the following code

def matrix_input(3):
    matrix = []
    for i in range(N):
        a = nd.array(input().split(),int)
        matrix.append(a)
    print(matrix)

But I'm getting the following output: [array([1, 1, 1]), array([1, 1]), array([1, 1, 1])]

For the input:

1 1 1 
 1 1 
1 1 1 

I don't want the matrix to have the word array in them... How do I remove it?

Upvotes: 1

Views: 81

Answers (1)

Tanmaya Meher
Tanmaya Meher

Reputation: 1476

Make it a list on the 4th line of your code. Also, correct your function as mentioned in the code below. Function call and function creation are two different things, so does the arguments you pass into it.

import numpy as np

def matrix_input(N):  # Argument to function while creation is wrong, use N instead of 3.
    matrix = []
    for i in range(N):
        a = list(np.array(input().split(),int))  # Make it a list here
        matrix.append(a)
    print(matrix)

output:

matrix_input(3)
1 1 1
1 1
1 1 1

[[1, 1, 1], [1, 1], [1, 1, 1]]

Alternative method for creating a Proper matrix :

import numpy as np

matrix_1 = np.matrix([[1,1,1],[1,1,0],[1,1,1]])
print(matrix_1)

Output:

[[1 1 1]
 [1 1 0]
 [1 1 1]]

Upvotes: 1

Related Questions