How to create matrix in Python
A Matrix is a rectangular array of data or numbers. The horizontal entries in a matrix are called as ‘rows’ while the vertical entries are called as ‘columns’. If matrix has m number of rows and n number of columns, then the order of the matrix is given as m x n.
Lets go through some methods for creating matrix in Python.
Method 1:
m = int(input("No. of rows: ")) n = int(input("No. of columns: ")) matr = [] print("Enter the entries rowwise:") for i in range(m): #loop for row entries x = [] for j in range(n): #loop for column entries x.append(int(input())) matr.append(x) #printing matrix for i in range(m): for j in range(n): print(matr[i][j], end=" ") print()
Output:
No. of rows: 2 No. of columns: 3 Enter the entries rowwise: 1 2 3 4 5 5 1 2 3 4 5 5
Method 2: Using map()
function and Numpy
.
NumPy is a Python library for scientific computations and multidimensional arrays. We can use NumPy to create matrix.
import numpy as np m = int(input("No. of rows: ")) n = int(input("No. of columns: ")) matr = [] print("Enter the entries in single line separated by space:") ele = list(map(int,input().split())) #printing matrix matrix = np.array(ele).reshape(m, n) print(matrix)
Output:
No. of rows: 3 No. of columns: 4 Enter the entries in single line separated by space: 1 2 3 4 5 6 7 8 9 10 11 12 [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]]
Subscribe
Login
Please login to comment
0 Discussion