Home » How to take Matrix Input from User in Python

How to take Matrix Input from User in Python

by Online Tutorials Library

How to take Matrix Input from User in Python

In this tutorial, we’ll discuss ways to receive matrix input from the user in Python. Input from the client can be obtained in two ways. Let’s take a look at two of them.

Matrix

The term “matrix” refers to a rectangular distribution of data and perhaps numbers. It’s a rectangular/square array of data or numbers, in other words. In a matrix, the horizontal entries are referred to as ‘rows,’ while the vertical elements are referred to as ‘columns.’ The order of a matrix is defined as “r x c” if it has “r” rows and “c” columns. Each entry in a matrix could be an integer, a floating point value, or even a complex number.

Example:

Ways to take Matrix as Input

We can accept a user input matrix in Python in a variety of ways. The following are some of the Python user input matrix methods:

Method – 1

We can use “for loop” inside a for loop to take arrange both rows and columns of a matrix of size given by the user.

Input

Output:

Give the number of rows:2  Give the number of columns:3  Please give the entries row-wise:  3  5  2  7  4  6  3 5 2   7 4 6  

To write the two for loops in a line:

Input

Output:

Give the number of rows:2  Give the number of columns:3  4  2  6  3  6  3  [[4, 2, 6], [3, 6, 3]]  

Method – 2

Numpy and the map() function are being used.

NumPy, a prominent Python package, is one of the most widely used. This library is a must-have for any scientific computing project. It’s also useful for multidimensional arrays, and because a matrix is indeed a rectangular array, we’ll utilize it for user input.

Input

Output:

Give the number of rows:2  Give the number of columns:3  Please write the elements of the matrix in a single line and seperated by a space:   3 4 5 3 7 5  [[3 4 5]   [3 7 5]]  

Method – 3

Using space-separated values, one row at a time. And then using the map() and int functions to convert each of them. Look at the code.

Input

Output:

Give the number of rows:2  Give the number of columns:3  5 3 7  3 5 2  [[5, 3, 7], [3, 5, 2]]  

You may also like