Python program written using multidimensional arrays to add two matrices

王林
Release: 2023-09-04 09:37:06
forward
1774 people have browsed it

Python program written using multidimensional arrays to add two matrices

A matrix is ​​a two-dimensional array of numbers arranged in rows and columns. The addition of two matrices is to add the corresponding elements of the two matrices and place the sum at the corresponding position of the resulting matrix. This is only possible if the number of rows and columns of both matrices are equal.

In Python, multidimensional arrays are created using lists or NumPy arrays. List data structure can accept lists as elements so we can easily create matrices. Additionally, the Numpy module provides a variety of methods for working with multidimensional arrays.

Input and output scenarios

Addition of two matrices

[a11, a12, a13]	   [b11, b12, b13]		[a11+b11, a12+b12, a13+b13]
[a21, a22, a23]  + [b21, b22, b23]	=	[a21+b21, a22+b22, a23+b23]
[a31, a32, a33]	   [b31, b32, b33]		[a31+b31, a32+b32, a33+b33]
Copy after login

In this article, we will learn how to add two matrices using multidimensional arrays in python.

Use for loop

Here, we will use nested for loops to iterate through each row and column of the given input matrix. In each iteration, we will add the corresponding elements of the two input matrices and store them in the result matrix.

Example

# Defining the matrix using multidimensional arrays
matrix_a = [[1,2,3],
            [4 ,5,6],
            [7 ,8,9]]
 
matrix_b = [[1,2,3],
            [4 ,5,6],
            [7 ,8,9]]

#function for displaying matrix
def display(matrix):
   for row in matrix:
      print(row)
   print()

# Display two input matrices
print('The first matrix is defined as:') 
display(matrix_a)
print('The second matrix is defined as:')
display(matrix_b)

# Initializing Matrix with all 0s
result = [[0, 0, 0],[0, 0, 0],[0, 0, 0]]

# Add two matrices 
for i in range(len(matrix_a)): 

   # iterate through rows 
   for j in range(len(matrix_a[0])):

      # iterate through columns
      result[i][j] = matrix_a[i][j] + matrix_b[i][j]

print('The addition of two matrices is:')
display(result)
Copy after login

Output

The first matrix is defined as:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

The second matrix is defined as:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

The addition of two matrices is:
[2, 4, 6]
[8, 10, 12]
[14, 16, 18]
Copy after login

Store the sum of corresponding elements of the two input matrices in the result matrix we originally created with all zeros.

Use list comprehension

List comprehension provides the shortest syntax to build a list without initializing an empty list before a for loop to append values ​​one by one.

Example

This example works similarly to the previous example, except that we use a list comprehension instead of creating a resulting matrix of all zeros.

# Defining the matrix using multidimensional arrays
matrix_a = [[1,2,5],
            [1,0,6],
            [9,8,0]]
 
matrix_b = [[0,3,5],
            [4,6,9],
            [1,8,0]]

#function for displaying matrix
def display(matrix):
   for row in matrix:
      print(row)
   print()

# Display two input matrices
print('The first matrix is defined as:') 
display(matrix_a)
print('The second matrix is defined as:')
display(matrix_b)

# Add two matrices 
result = [[matrix_a[i][j] + matrix_b[i][j]  for j in range(len(matrix_a[0]))] for i in range(len(matrix_a))]    

print('The addition of two matrices is:')
display(result)
Copy after login

Output

The first matrix is defined as:
[1, 2, 5]
[1, 0, 6]
[9, 8, 0]

The second matrix is defined as:
[0, 3, 5]
[4, 6, 9]
[1, 8, 0]

The addition of two matrices is:
[1, 5, 10]
[5, 6, 15]
[10, 16, 0]
Copy after login

Using NumPy arrays

The NumPy module in Python has many built-in functions to handle multi-dimensional arrays. By using these arrays we can easily add two matrices.

Example

In this example, we will use the numpy.array() method to create two multidimensional arrays. Then apply the addition operator between the two arrays.

import numpy as np

# Defining the matrix using numpy array
matrix_a = np.array([[1,2,5], [1,0,6], [9,8,0]])
matrix_b = np.array([[0,3,5], [4,6,9], [1,8,0]])

# Display two input matrices
print('The first matrix is defined as:') 
print(matrix_a)

print('The second matrix is defined as:')
print(matrix_b)

# Add two matrices
result = matrix_a + matrix_b

print('The addition of two matrices is:')
print(result)
Copy after login

Output

The first matrix is defined as:
[[1 2 5]
 [1 0 6]
 [9 8 0]]
The second matrix is defined as:
[[0 3 5]
 [4 6 9]
 [1 8 0]]
The addition of two matrices is:
[[ 1  5 10]
 [ 5  6 15]
 [10 16  0]]
Copy after login

We simply apply the addition operator ( ) between numpy arrays matrix_a and matrix_b to add multidimensional arrays.

The above is the detailed content of Python program written using multidimensional arrays to add two matrices. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!