Matrix addition in python

Matrix Addition and Subtraction in Python

Matrix Addition and Subtraction in Python | Here, we will discuss matrix addition and subtraction in python. For adding and subtracting any two matrices, both the matrices should be of the same dimension; we carry out the addition by adding corresponding elements together. Similar to the add operation, we can also implement other mathematical operations.

  1. Matrix Addition And Subtraction In Python Using Numpy
  2. Matrix Addition And Subtraction In Python User Input
  3. Matrix Addition And Subtraction In Python Using Function
  4. Matrix Addition And Subtraction In Python Using Nested Loop

Python Program to Add and Subtract Two Matrices using NumPy

Numpy is a library in python which has several functions that make it easy for the programmer to concentrate on the logic part. In this section, we use NumPy for the addition and subtraction of two matrices in python.

In the code, we have imported NumPy as np then declared matrix 1 and matrix 2 as m1 and m2 respectively by using numpy.add() and numpy.subtract(). We add and subtract m1 and m2 and store the result in r.

Program description:- Write a python program to add and subtract two matrices

# Python program to add and subtract two matrices import numpy as np m1 = np.array([[1, 3, 4], [8, 5, 6]]) m2 = np.array([[8, 6, 9], [9, 0, 6]]) print("Add Matrix:") a = np.add(m1, m2) print(a) print("Subtract Matrix:") b = np.subtract(m2, m1) print(b)

Add Matrix:
[[ 9 9 13][17 5 12]]Subtract Matrix:
[[ 7 3 5][ 1 -5 0]]

Matrix Addition and Subtraction in Python User Input

Here we add and subtract matrices by taking user input, we use a list and map. We use lists to store multiple items of a single variable, it is one of the data types in python. A map is an inbuilt function that allows us to process and transform all the items in an iterable without using a loop.

# Python program to add and subtract two matrix # take first matrix inputs m1 = [list(map(int, input("Enter row: ").split(" "))) for i in range(int(input("Enter Number of rows: ")))] # take second matrix inputs m2 = [list(map(int, input("Enter row: ").split(" "))) for i in range(int(input("Enter Number of rows:")))] # add these matrix print("Add Matrix:") r = [[m1[i][j] + m2[i][j] for j in range(len(m1[0]))] for i in range(len(m1))] print(r) # subtract these matrix print("Subtract Matrix:") r = [[m1[i][j] - m2[i][j] for j in range(len(m1[0]))] for i in range(len(m1))] print(r)

Enter Number of rows: 2
Enter row: 9 8
Enter row: 7 6
Enter Number of rows:2
Enter row: 5 4
Enter row: 3 2
Add Matrix:
[[14, 12], [10, 8]]Subtract Matrix:
[[4, 4], [4, 4]]

In the above code, we first take the matrix from the user and store it in m1, then similarly we take m2 and we read all the row elements as well. Then we add and subtract both the matrix and put it in the result. While adding and subtracting, we use a for loop to check whether the dimension is the same or not.

Читайте также:  Raspberry pi run python script

In the output shown first it takes the number of rows for matrix 1 and reads the matrix elements similarly it is done for matrix 2 then it adds, subtracts, and gives the result.

Matrix Addition and Subtraction in Python using Function

In python we can define our own function, so by using this we can add and subtract two matrices. Here in the below code, we have defined a function called add() and subtract() which takes two parameters m1 and m2.

def add(m1, m2): new = [] for i in range(0, len(m1)): new.append(m1[i] + m2[i]) return new def subtract(m1, m2): new = [] for i in range(0, len(m1)): new.append(m1[i] - m2[i]) return new # main m1 = [[9, 2], [2, 5]] m2 = [[1, 4], [0, 3]] c = [] for i in range(0, len(m1)): c.append(add(m1[i], m2[i])) print("Add Matrix:") print(c) c = [] for i in range(0, len(m1)): c.append(subtract(m1[i], m2[i])) print("Subtract Matrix:") print(c)

Add Matrix:
[[10, 6], [2, 8]]Subtract Matrix:
[[8, -2], [2, 2]]

In the add() and subtract() function, we initiate new to an empty array, then we append new to the addition and subtraction of matrix 1 and matrix2. Then in the main function, we take two matrices and then call add() and subtract() to add and subtract the matrices and store them in c.

Matrix Addition Program in Python using a Nested Loop

A nested loop is a loop inside another loop. In this example, we use nested for-loops to add and subtract matrices.

Program description:- Python program to add and subtract two matrices taking input from a user

# Python program to add and subtract two matrices r = int(input("Enter the rows: ")) c = int(input("Enter the columns: ")) print("Enter Matrix 1:") m1 = [[int(input()) for i in range(c)] for i in range(r)] print("Matrix 1 is: ") for n in m1: print(n) print("Enter Matrix 2:") m2 = [[int(input()) for i in range(c)] for i in range(r)] for n in m2: print(n) r = [[0 for i in range(c)] for i in range(r)] for i in range(len(r)): for j in range(c): r[i][j] = [m1[i][j] + m2[i][j]] print("Add Matrix:") for i in r: print(i) for i in range(len(r)): for j in range(c): r[i][j] = [m1[i][j] - m2[i][j]] print("Subtract Matrix:") for i in r: print(i)

In the above code, we have used a nested for loop to add m1 and m2. The outer loop reads the row elements the inner loop reads the column elements and stores the result in r.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Python Matrix Addition

In Python, a Matrix can be represented using a nested list. Lists inside the list are the rows.

Following is a simple example of nested list which could be considered as a 2×3 matrix.

The two lists inside matrixA are the rows of the matrix. Number of elements inside a row represent the number of columns.

Also, in Python programming, the indexing start from 0. So, when we specify matrixA[2][4] in the program, that is actually [2+1][4+1] = [3][5], element of third row and fifth column.

As we are using Lists to represent matrices, you should be careful with the results of arithmetic operator for two lists.

Читайте также:  Python matplotlib legend size

For example, in the following statement, the result of addition operator does not return a list of element by element addition of the two operands, but returns a list with the inner lists of second operand appended to the elements of first operand.

matrixC = matrixA + matrixB // where these are nested lists

To compute the addition of two matrices, which are list of lists in Python, you have to traverse through the rows and columns, and compute the addition.

In this tutorial, we will learn how to do Matrix Addition in Python using Lists.

Examples

1. Add two matrices using For Loop

In this example, we shall take two matrices and compute their addition. We shall use Python For Loop to traverse through all the elements of a matrix.

Python Program

matrixA = [ [2, 1, 3], [3, 1, 5] ] matrixB = [ [1, 4, 2], [5, 2, 0] ] #matrix where we shall store our result #intialize this to 0, with size as that of matrixA or matrixB matrixC = [[0 for i in range(len(matrixA[0]))] for j in range(len(matrixA))] #for each row in the matrix for i in range(len(matrixB)): #for each element in the row for j in range(len(matrixB[0])): matrixC[i][j] = matrixA[i][j] + matrixB[i][j] print(' matrixA:', matrixA) print('+ matrixB:', matrixB) print('-------------------------------') print(' matrixC:', matrixC)
 matrixA: [[2, 1, 3], [3, 1, 5]] + matrixB: [[1, 4, 2], [5, 2, 0]] ------------------------------- matrixC: [[3, 5, 5], [8, 3, 5]]

2. Add two matrices using List Comprehension

In this example, we shall take two matrices and compute their addition. We shall use Python List Comprehension to compute addition at element level.

Python Program

matrixA = [ [2, 1, 3], [3, 1, 5] ] matrixB = [ [1, 4, 2], [5, 2, 0] ] matrixC = [[matrixA[i][j] + matrixB[i][j] for j in range(len(matrixA[0]))] for i in range(len(matrixA))] print(' matrixA:', matrixA) print('+ matrixB:', matrixB) print('-------------------------------') print(' matrixC:', matrixC)

The code for addition of matrices using List Comprehension is very concise.

 matrixA: [[2, 1, 3], [3, 1, 5]] + matrixB: [[1, 4, 2], [5, 2, 0]] ------------------------------- matrixC: [[3, 5, 5], [8, 3, 5]]

Summary

In this tutorial of Python Examples, we learned how to do Matrix Addition in Python using For loop and List comprehension, with the help of well detailed examples.

Источник

Matrix Addition in Python | Addition of Two Matrices

Matrix addition in python

Hello Programmers, today’s article is about matrix addition in python. We will discuss different ways of adding two matrices in python. Matrix addition in python means adding up the elements of one matrix with another. The added up elements are then stored in a third matrix.

Matrix addition in Python is a technique by which you can add two matrixes of the same shape. If the matrices don’t have the same shape, the addition will not be possible. Moreover, the addition in matrices works one way, which means that the (1,1) element will only add to (1, 1) element of another matrix.

Before we start with different ways of matrix addition, let me just cite an example of matrix addition for you.

Let A and B be two matrices which are added and the result is stored in a new matrix C.

A = [ [1, 2, 3], [4, 5, 6] ] B = [ [6, 5, 4], [3, 2, 1] ] C = [ [7, 7, 7], [7, 7, 7] ]

The elements of C matrix are sum of the elements of A and B matrix i.e.,

Читайте также:  Number methods in javascript

Different ways of matrix addition in python:

  • Using Nested for loop
  • Use of Nested list Comprehension
  • With sum and zip() function
  • Using NumPy

Matrix Addition using Nested for loop

iterate through columns for j in range(len(A[0])): result[i][j] = A[i][j] + B[i][j] for x in result: print(x)

EXPLANATION:

In this example, nested for loops are used to iterate through each row and columns of the given matrices. After each iteration, we add the corresponding elements of the A and B matrix. And store the sum in the third matrix called result.

Using Nested List Comprehension method

A = [[1,2,3], [4 ,5,6], [7 ,8,9]] B = [[9,8,7], [6,5,4], [3,2,1]] result = [[A[i][j] + B[i][j] for j in range (len(A[0]))] for i in range(len(A))] for r in result: print(r)

EXPLANATION:

List comprehension means nested list, i.e., list inside a list. This method is used to implement a matrix as a nested list. In this example, list comprehension is used for iterating through each element of the given matrices. List comprehension method of matrix addition in python helps writing concise and to the point codes. Thus, it makes the codes of matrix addition simpler and helpful.

Matrix Addition with Sum and zip() function

A = [[1,2,3], [4 ,5,6], [7 ,8,9]] B = [[9,8,7], [6,5,4], [3,2,1]] result = [map(sum, zip(*i)) for i in zip(X, Y)] print(result)
[[10, 10, 10], [10, 10, 10], [10, 10, 10]]

EXPLANATION:

The zip() function’s function is to accept iterator of each element of the matrix, map them, and add them using the sum() function. It returns and stores the result in the mapping form.

Matrix addition using NumPy

import numpy as np import random # Routine for printing a 2x2 matrix def PrintMatrix(matrix_in): for x in range(0, matrix_in.shape[0]): for y in range(0, matrix_in.shape[1]): print("%d \t"%(matrix_in[x][y]), end='' if(y%3>1): print("\n") # Function to populate a 2x2 matrix with random data def FillMatrix(matrix_in): for x in range(0, matrix_in.shape[0]): for y in range(0, matrix_in.shape[1]): matrix_in[x][y] = random.randrange(2, 10) + 2 # Create matrices using ndarray matrix1 = np.ndarray((3,3)) matrix2 = np.ndarray((3,3)) # Fill the matrices i.e., the two dimensional arrays created using ndarray objects FillMatrix(matrix1) FillMatrix(matrix2) # Add two matrices - two nd arrays add_results = matrix1.__add__(matrix2) # Print Matrix1 print("Matrix1:") PrintMatrix(matrix1) # Print Matrix2 print("Matrix2:") PrintMatrix(matrix2) # Print the results of adding two matrices print("Result of adding Matrix1 and Matrix2:") PrintMatrix(add_results)
Matrix1: [1 2 3 4 5 6 7 8 9] Matrix2: [9 8 7 6 5 4 3 2 1] Result of adding Matrix1 and Matrix2: [10 10 10 10 10 10 10 10 10]

EXPLANATION:

The first condition for adding two matrices is that both the matrices should have the same number of rows and columns. The result thus obtained also has the same number of rows and columns. The ndarray of the NumPy module helps create the matrix. The method __add__() provided by the ndarray of the NumPy module performs the matrix addition . The __add__ () function adds two ndarray objects of the same shape and returns the sum as another ndarray object.

Must Read

Conclusion:

This article gives an insight into different ways of matrix addition in python. You can use any of the above ways as per your need and convenience. Using List Comprehension is one of the simplest and concise methods of matrix addition. This method is helpful and must be included quite frequently in python programs.

Still have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Источник

Оцените статью