Python program to take Matrix input from user


A matrix is a rectangular array or table of numbers arranged in rows and columns, these numbers are called elements or entries of the matrix. The horizontal entries of the matrix are called rows and vertical entries are known as columns.

Suppose a matrix has m rows and n columns then we can say that this matrix is of order mxn. The following is the example of a 3×4 matrix –

3x4 matrix

In this article, I will show you the Python program to take matrix input from the user and print it to standard output.

Python program to take matrix input

The following program shows how to take input of matrix element for a user and print it in the terminal –

## Python program to take matrix input

#Take dimension of matrix
m = int(input("Enter the number of rows:"))
n = int(input("Enter the number of columns:"))

# Initializing empty matrix
A = []


# Matrix A user input
print (" \n Enter matrix elements(row wise): \n")
for i in range(m):
	a =[]
	for j in range(n):
		a.append(int(input()))
	A.append(a)


# Print matrix A
print (" \nYou have entered the given matrix  \n")
for i in range(m):
	for j in range(n):
		print(A[i][j], end = " ")
	print()

Save the program with .py extension and run using the given command –

python3 /home/lalit/python_programs/matrix_input

output

Taking user input with map()

You can use another method i.e. by using the NumPy library and map() function to take user input of matrix.

The following program shows the use of NumPy and map() –

## Python program to take user input with numpy and map()

import numpy as np

m = int(input("Enter the number of rows:"))
n = int(input("Enter the number of columns:"))


print("Enter matrix elements separated by space in single line: ")
matrix_elements = list(map(int, input().split()))

# Print the matrix

matrix = np.array(matrix_elements).reshape(m,n)
print("\nYou have entered the given matrix: \n")
print(matrix)

When you execute this program it will display the given output –

output

You can extend this code to take input for multiple matrices. Now if you have a query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.