Python: Creating a Matrix with Keyboard Input

Reading Time: 4 Minutes
Publication date:

In programming, a matrix is a two-dimensional array consisting of elements arranged in a specific order. Creating and inputting a matrix in the Python programming language is an important task for data manipulation. In this article, we will explore how to create and populate a matrix using the keyboard.

Creating a matrix can be done using lists in Python. Each row of the matrix is represented by a separate list of elements. For example, a 3×3 matrix can be represented by a list of lists:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

To input matrix elements from the keyboard, nested loops can be used to iterate through all rows and columns of the matrix. Each element can be assigned to the corresponding index in the two-dimensional list.

After entering all the elements of the matrix, various operations can be performed with the data, such as processing, sorting, or analysis. Creating a matrix and entering elements via the keyboard allows for more flexible data handling and analysis in a Python program.

How to Create and Enter a Matrix in Python?

A matrix is a two-dimensional array or table of numbers used for storing and processing data. In Python, creating and inputting a matrix can be done using several methods.

Method 1: Manually Creating a Matrix with Nested Lists

To create a 3×3 matrix manually, we can write the following code:

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In this example, we create a matrix consisting of three rows and three columns.

Method 2: Creating a Matrix Using the zeros Function from the numpy Library

To do this, we need to import the library and call the function, specifying the dimensions of the matrix. For example, to create a 2×4 matrix, we can write the following code:

import numpy as np

matrix = np.zeros((2, 4))

In this example, we create a matrix consisting of two rows and four columns, filled with zeros.

Method 3: Inputting a Matrix from the Keyboard Using the input Function

For example, the following code allows the user to enter a 3×3 matrix:

matrix = []

for i in range(3):
    row = [int(x) for x in input().split()]
    matrix.append(row)

In this example, we create an empty list matrix and fill it with rows entered by the user using the input function. Each row is split into separate numbers using the split function, which divides the input into parts based on spaces. Then, we convert each part into an integer using the list comprehension [int(x) for x in input().split()]. Each row is then added to the matrix list.

Now you know how to create and enter a matrix in Python using various methods. You can choose the most convenient method depending on your needs and preferences.

Creating and Initializing a Matrix in Python

  1. The simplest way is to create an empty matrix of fixed size. This can be done using the zeros() or empty() method from the numpy module, or by creating a two-dimensional list and filling it with zeros or empty values: import numpy as np # Creating an empty 3x3 matrix matrix = np.zeros((3, 3)) # or matrix = np.empty((3, 3)) # Creating an empty 3x3 matrix using a two-dimensional list matrix = [[0 for _ in range(3)] for _ in range(3)] # or matrix = [[None for _ in range(3)] for _ in range(3)]
  2. You can create and initialize a matrix with values immediately upon creation. This can be done using the array() method from the numpy module or by creating a two-dimensional list and filling it with the required values: import numpy as np # Creating a matrix with specified values matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # or matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
  3. If you need to create a large matrix with the same value, you can use the tile() or repeat() functions from the numpy module: import numpy as np # Creating a 4x4 matrix of ones matrix = np.tile(1, (4, 4)) # or matrix = np.repeat([[1]], 4, axis=0)

These are just a few possible ways to create and initialize a matrix in Python. The choice of method depends on the needs and preferences of the programmer.

Schedule

DaySubject
MondayMathematics
TuesdayPhysics
WednesdayBiology
ThursdayChemistry
FridayGeography

Entering a Matrix from the Keyboard in Python

To start working with a matrix, you need to determine its dimensions, i.e., the number of rows and columns. Then, you can use loops to input data from the keyboard for each element of the matrix.

Example Code for Creating and Entering a Matrix

# Define the dimensions of the matrix
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))

# Create an empty matrix of the given dimensions
matrix = []

# Loop to input data from the keyboard
for i in range(rows):
    row = []
    for j in range(cols):
        element = int(input("Enter the matrix element [" + str(i) + "][" + str(j) + "]: "))
        row.append(element)
    matrix.append(row)

In this example, an empty matrix of dimensions specified by the user is created. Then, using nested loops and the input() function, matrix elements are entered and added to the corresponding rows and columns of the matrix.

After completing the input, the matrix will be stored in the matrix variable and can be used in the further program.

Now you know how to input a matrix from the keyboard in Python. This method provides flexibility and allows you to work with matrices entered by the user.

Examples of Using Matrices in Python Programming

Example 1: Creating a Tic-Tac-Toe Game Board

Using a matrix, you can easily display the game board and track players’ moves. Each cell of the matrix will represent a separate cell on the game board.

Example 2: Finding a Path in a Maze

A matrix can be used to represent a maze, where each cell can be either free or blocked. Using a search algorithm, you can find the shortest path from the start to the end point.

Example 3: Finding the Sum of Elements in a Two-Dimensional Array

Using loops and conditional operators, you can iterate through all elements of the matrix and find their sum.

Example 4: Computer Graphics Transformations

In computer graphics, matrices can be used for transformations and object manipulation. For example, a matrix can be used for rotating, scaling, or translating an object on a plane.

These examples demonstrate just a few possibilities of using matrices in Python programming. With matrices, you can solve many tasks in various fields, such as data analysis, machine learning, computer graphics, and more.

5 / 5. 1

Share:

Leave a comment