top of page

Python Native Data Type Programs

1) 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 2x3 matrix then it can be shown like this:

2       3          5  

8       12        7  

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 3x2 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:

X = [[1,2,3],  

    [4,5,6],  

    [7,8,9]]  

  

Y = [[10,11,12],  

    [13,14,15],  

    [16,17,18]]  

Create a new matrix result by adding them.

See this example:

back.png

# iterate through rows  

for i in range(len(X)):  

   # iterate through columns  

   for j in range(len(X[0])):  

       result[i][j] = X[i][j] + Y[i][j]  

for r in result:  

   print(r)  

2) Python Program to Multiply Two Matrices

This Python program specifies how to multiply two matrices, having some certain values.

Matrix multiplication:

Matrix multiplication is a binary operation that uses a pair of matrices to produce another matrix. The elements within the matrix are multiplied according to elementary arithmetic.

See this example:

back.png

# iterate through rows of X  

for i in range(len(X)):  

   for j in range(len(Y[0])):  

       for k in range(len(Y)):  

           result[i][j] += X[i][k] * Y[k][j]  

for r in result:  

   print(r)  

bottom of page