Aman
Aman

Reputation: 131

python program to generate n*n matrix from user input

I want to generate a n*n matrix from user inputing the value of n and elements of the matrix.

Following is the code:

n=int(input("Enter the matrix size"))

import numpy as np

#initialise nxn matrix with zeroes
mat=np.zeros((n,n))

#input each row at a time,with each element separated by a space
for i in range(n):
    for j in range(n):
        mat[i][j]=input()
print(mat)  

but I am getting output like this

[[1. 2.]

 [3. 4.]]

with a . (point) after the numbers which I don't want. Is there any way to get this with using loops and array only not NumPy?

Upvotes: 3

Views: 1351

Answers (4)

Harish Yadav
Harish Yadav

Reputation: 11

m=int(input("enter matrix row size"))
n=int(input("enter matrix column size"))

Mat1 = []
Mat2 = []
Mat3 = []

for i in range(m):
    Mat1.append([0]*n)
print (Mat1)

for j in range(m):
    Mat2.append([0]*n)
print (Mat2)

for k in range(m):
    Mat3.append([0]*n)
print (Mat3)


for i in range(m):
    for j in range(n):
        print ('enter in Matrix 1 row: ',i+1,' column: ',j+1)
        Mat1[i][j] = int(input())

for k in range(m):
    for l in range(n):
        print ('enter in MAtrix 2 row: ',k+1,' column: ',l+1)
        Mat2[k][l] = int(input())

for p in range (m):
    for q in range (n):
        Mat3[p][q]=Mat1[p][q]+Mat2[p][q]
        #print(Mat1[p][q]+Mat2[p][q])`z

print (Mat1)        
print (Mat2)
print (Mat3)

Upvotes: 0

Abhish
Abhish

Reputation: 67

You can use this:

n =  int(input())

mat=[[int(input()) for x in range(n)] for i in range(n)]

You can convert above list into numpy as

np_mat = numpy.asarray(mat)

If you want to input each row at a time,with each element separated by a space, you can do like this.

mat=[list(map(int, input().split())) for i in range(n)]

Upvotes: 2

Shan
Shan

Reputation: 399

It's because np.zeros by default assigns it's values to float. To change that replace line: mat=np.zeros((n,n))

with:

mat=np.zeros((n,n), dtype=int)

It will give you output you want.

Also good practice is to use help() on used methods, to know what can be done with them, like in this example.

Upvotes: 5

Sheldore
Sheldore

Reputation: 39062

You were almost close. You just have to declare the datatype as dtype=int while initializing your matrix as

mat=np.zeros((n,n), dtype=int)

and then you won't have dots but just

[[1 2]
[3 4]]

Upvotes: 7

Related Questions