Matrix addition and multiplication in python

In Python, we can implement a matrix as nested list (list inside a list).

We can treat each element as a row of the matrix.

For example X = [[1, 2], [4, 5], [3, 6]] would represent a 3x2 matrix.

The first row can be selected as X[0]. And, the element in first row, first column can be selected as X[0][0].

Multiplication of two matrices X and Y is defined only if the number of columns in X is equal to the number of rows Y.

If X is a n x m matrix and Y is a m x l matrix then, XY is defined and has the dimension n x l (but YX is not defined). Here are a couple of ways to implement matrix multiplication in Python.

Source Code: Matrix Multiplication using Nested Loop

# Program to multiply two matrices using nested loops

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
         [0,0,0,0],
         [0,0,0,0]]

# iterate through rows of X
for i in range(len(X)):
   # iterate through columns of Y
   for j in range(len(Y[0])):
       # iterate through rows of Y
       for k in range(len(Y)):
           result[i][j] += X[i][k] * Y[k][j]

for r in result:
   print(r)

Output

[114, 160, 60, 27]
[74, 97, 73, 14]
[119, 157, 112, 23]

In this program, we have used nested for loops to iterate through each row and each column. We accumulate the sum of products in the result.

This technique is simple but computationally expensive as we increase the order of the matrix.

For larger matrix operations we recommend optimized software packages like NumPy which is several (in the order of 1000) times faster than the above code.

Source Code: Matrix Multiplication Using Nested List Comprehension

# Program to multiply two matrices using list comprehension

# 3x3 matrix
X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

# 3x4 matrix
Y = [[5,8,1,2],
    [6,7,3,0],
    [4,5,9,1]]

# result is 3x4
result = [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*Y)] for X_row in X]

for r in result:
   print(r)

The output of this program is the same as above. To understand the above code we must first know about built-in function zip() and unpacking argument list using * operator.

We have used nested list comprehension to iterate through each element in the matrix. The code looks complicated and unreadable at first. But once you get the hang of list comprehensions, you will probably not go back to nested loops.

In this program, you'll learn to add two matrices using Nested loop and Next list comprehension, and display it.

To understand this example, you should have the knowledge of the following Python programming topics:

  • Python for Loop
  • Python List

In Python, we can implement a matrix as a nested list (list inside a list). We can treat each element as a row of the matrix.

For example X = [[1, 2], [4, 5], [3, 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].

We can perform matrix addition in various ways in Python. Here are a couple of them.

Source code: Matrix Addition using Nested Loop

# Program to add two matrices using nested loop

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

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

result = [[0,0,0],
         [0,0,0],
         [0,0,0]]

# 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)

Output

[17, 15, 4]
[10, 12, 9]
[11, 13, 18]

In this program we have used nested for loops to iterate through each row and each column. At each point, we add the corresponding elements in the two matrices and store it in the result.

Source Code: Matrix Addition using Nested List Comprehension

# Program to add two matrices using list comprehension

X = [[12,7,3],
    [4 ,5,6],
    [7 ,8,9]]

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

result = [[X[i][j] + Y[i][j]  for j in range(len(X[0]))] for i in range(len(X))]

for r in result:
   print(r)

The output of this program is the same as above. We have used nested list comprehension to iterate through each element in the matrix.

List comprehension allows us to write concise codes and we must try to use them frequently in Python. They are very helpful.


Given two user input matrix. Our task is to display the addition of two matrix. In these problem we use nested List comprehensive.

Algorithm

Step1: input two matrix.
Step 2: nested for loops to iterate through each row and each column.
Step 3: take one resultant matrix which is initially contains all 0. Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value. That is the value of resultant matrix.

Example Code

# Program to multiply two matrices
A=[]
n=int(input("Enter N for N x N matrix: "))         
print("Enter the element ::>")
for i in range(n): 
   row=[]                                      #temporary list to store the row
   for j in range(n): 
      row.append(int(input()))           #add the input to row list
      A.append(row)                      #add the row to the list
print(A)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
   for j in range(n):
      print(A[i][j], end=" ")
   print()                                        #new line
B=[]
n=int(input("Enter N for N x N matrix : "))           #3 here
#use list for storing 2D array
#get the user input and store it in list (here IN : 1 to 9)
print("Enter the element ::>")
for i in range (n): 
   row=[]                                      #temporary list to store the row
   for j in range(n): 
      row.append(int(input()))           #add the input to row list
      B.append(row)                       #add the row to the list
print(B)
# [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
#Display the 2D array
print("Display Array In Matrix Form")
for i in range(n):
   for j in range(n):
      print(B[i][j], end=" ")
   print()                                           
result = [[0,0,0], [0,0,0], [0,0,0]] 
for i in range(len(A)): 
   for j in range(len(B[0])): 
      for k in range(len(B)): 
         result[i][j] += A[i][k] * B[k][j] 
print("The Resultant Matrix Is ::>")
for r in result: 
   print(r) 

Output

Enter N for N x N matrix: 3
Enter the element ::>
2
1
4
2
1
2
3
4
3
[[2, 1, 4], [2, 1, 2], [3, 4, 3]]
Display Array In Matrix Form
2 1 4 
2 1 2 
3 4 3 
Enter N for N x N matrix : 3
Enter the element ::>
1
2
3
4
5
6
7
8
9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Display Array In Matrix Form
1 2 3 
4 5 6 
7 8 9 
The Resultant Matrix Is ::>
[34, 41, 48]
[20, 25, 30]
[40, 50, 60]

Matrix addition and multiplication in python

Updated on 30-Jul-2019 22:30:23

  • Related Questions & Answers
  • Python program addition of two matrix
  • C++ Program to Perform Matrix Multiplication
  • C Program for Matrix Chain Multiplication
  • Matrix Chain Multiplication
  • Matrix multiplication algorithm
  • Matrix Multiplication and Normalization in C program
  • Multiplication of two Matrices using Numpy in Python
  • Multiplication of two Matrices using Java
  • Sparse Matrix Multiplication in C++
  • Matrix Vector multiplication with Einstein summation convention in Python
  • Algorithm for matrix multiplication in JavaScript
  • Take in two 2-D arrays of numbers and returns their matrix multiplication result- JavaScript
  • Multiplication of two Matrices in Single line using Numpy in Python
  • C++ Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
  • Construct a TM performing multiplication of two unary numbers

How do you do matrix addition in Python?

Step1: input two matrix. Step 2: nested for loops only to iterate through each row and columns. Step 3: At each iterationshall add the corresponding elements from two matrices and shall store the result.

How do you write a matrix multiplication program in Python?

Step1: input two matrix. Step 2: nested for loops to iterate through each row and each column. Step 3: take one resultant matrix which is initially contains all 0. Then we multiply each row elements of first matrix with each elements of second matrix, then add all multiplied value.

Does Python do matrix multiplication?

In Python, @ is a binary operator used for matrix multiplication.

How do you do matrix multiplication in NumPy Python?

import numpy as np..
# two dimensional arrays..
m1 = np. array([[1,4,7],[2,5,8]]).
m2 = np. array([[1,4],[2,5],[3,6]]).
m3 = np. dot(m1,m2).
print(m3).
# three dimensional arrays..