Python Program to Add Two Matrices

Created with Sketch.

Python Program to Add Two Matrices

What is Matrix?

In mathematics, matrix is a rectangular array of numbers, symbols or expressions arranged in the form of rows and columns. For example: if you take a matrix A which is a 2×3 matrix then it can be shown like this:

  1. 2       3          5
  2. 8       12        7

Image representation:

Python Nativ Data Programs1

In Python, matrices can be implemented as nested list. Each element of the matrix is treated as a row. For example X = [[1, 2], [3, 4], [5, 6]] would represent a 3×2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0].

Let’s take two matrices X and Y, having the following value:

  1. X = [[1,2,3],
  2.     [4,5,6],
  3.     [7,8,9]]
  4. Y = [[10,11,12],
  5.     [13,14,15],
  6.     [16,17,18]]

Create a new matrix result by adding them.

See this example:

  1. X = [[1,2,3],
  2.        [4,5,6],
  3.        [7,8,9]]
  4. Y = [[10,11,12],
  5.        [13,14,15],
  6.        [16,17,18]]
  7. Result = [[0,0,0],
  8.                 [0,0,0],
  9.                 [0,0,0]]
  10. # iterate through rows
  11. for i in range(len(X)):
  12.    # iterate through columns
  13.    for j in range(len(X[0])):
  14.        result[i][j] = X[i][j] + Y[i][j]
  15. for r in result:
  16.    print(r)

Output:

Python Nativ Data Programs2

 

Leave a Reply

Your email address will not be published. Required fields are marked *