3

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?

0

4 Answers 4

7

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]]
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

2

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.