
- NumPy Tutorial
- NumPy - Home
- NumPy - Introduction
- NumPy - Environment
- NumPy Arrays
- NumPy - Ndarray Object
- NumPy - Data Types
- NumPy Creating and Manipulating Arrays
- NumPy - Array Creation Routines
- NumPy - Array Manipulation
- NumPy - Array from Existing Data
- NumPy - Array From Numerical Ranges
- NumPy - Iterating Over Array
- NumPy - Reshaping Arrays
- NumPy - Concatenating Arrays
- NumPy - Stacking Arrays
- NumPy - Splitting Arrays
- NumPy - Flattening Arrays
- NumPy - Transposing Arrays
- NumPy Indexing & Slicing
- NumPy - Indexing & Slicing
- NumPy - Indexing
- NumPy - Slicing
- NumPy - Advanced Indexing
- NumPy - Fancy Indexing
- NumPy - Field Access
- NumPy - Slicing with Boolean Arrays
- NumPy Array Attributes & Operations
- NumPy - Array Attributes
- NumPy - Array Shape
- NumPy - Array Size
- NumPy - Array Strides
- NumPy - Array Itemsize
- NumPy - Broadcasting
- NumPy - Arithmetic Operations
- NumPy - Array Addition
- NumPy - Array Subtraction
- NumPy - Array Multiplication
- NumPy - Array Division
- NumPy Advanced Array Operations
- NumPy - Swapping Axes of Arrays
- NumPy - Byte Swapping
- NumPy - Copies & Views
- NumPy - Element-wise Array Comparisons
- NumPy - Filtering Arrays
- NumPy - Joining Arrays
- NumPy - Sort, Search & Counting Functions
- NumPy - Searching Arrays
- NumPy - Union of Arrays
- NumPy - Finding Unique Rows
- NumPy - Creating Datetime Arrays
- NumPy - Binary Operators
- NumPy - String Functions
- NumPy - Matrix Library
- NumPy - Linear Algebra
- NumPy - Matplotlib
- NumPy - Histogram Using Matplotlib
- NumPy Sorting and Advanced Manipulation
- NumPy - Sorting Arrays
- NumPy - Sorting along an axis
- NumPy - Sorting with Fancy Indexing
- NumPy - Structured Arrays
- NumPy - Creating Structured Arrays
- NumPy - Manipulating Structured Arrays
- NumPy - Record Arrays
- Numpy - Loading Arrays
- Numpy - Saving Arrays
- NumPy - Append Values to an Array
- NumPy - Swap Columns of Array
- NumPy - Insert Axes to an Array
- NumPy Handling Missing Data
- NumPy - Handling Missing Data
- NumPy - Identifying Missing Values
- NumPy - Removing Missing Data
- NumPy - Imputing Missing Data
- NumPy Performance Optimization
- NumPy - Performance Optimization with Arrays
- NumPy - Vectorization with Arrays
- NumPy - Memory Layout of Arrays
- Numpy Linear Algebra
- NumPy - Linear Algebra
- NumPy - Matrix Library
- NumPy - Matrix Addition
- NumPy - Matrix Subtraction
- NumPy - Matrix Multiplication
- NumPy - Element-wise Matrix Operations
- NumPy - Dot Product
- NumPy - Matrix Inversion
- NumPy - Determinant Calculation
- NumPy - Eigenvalues
- NumPy - Eigenvectors
- NumPy - Singular Value Decomposition
- NumPy - Solving Linear Equations
- NumPy - Matrix Norms
- NumPy Element-wise Matrix Operations
- NumPy - Sum
- NumPy - Mean
- NumPy - Median
- NumPy - Min
- NumPy - Max
- NumPy Set Operations
- NumPy - Unique Elements
- NumPy - Intersection
- NumPy - Union
- NumPy - Difference
- NumPy Random Number Generation
- NumPy - Random Generator
- NumPy - Permutations & Shuffling
- NumPy - Uniform distribution
- NumPy - Normal distribution
- NumPy - Binomial distribution
- NumPy - Poisson distribution
- NumPy - Exponential distribution
- NumPy - Rayleigh Distribution
- NumPy - Logistic Distribution
- NumPy - Pareto Distribution
- NumPy - Visualize Distributions With Sea born
- NumPy - Matplotlib
- NumPy - Multinomial Distribution
- NumPy - Chi Square Distribution
- NumPy - Zipf Distribution
- NumPy File Input & Output
- NumPy - I/O with NumPy
- NumPy - Reading Data from Files
- NumPy - Writing Data to Files
- NumPy - File Formats Supported
- NumPy Mathematical Functions
- NumPy - Mathematical Functions
- NumPy - Trigonometric functions
- NumPy - Exponential Functions
- NumPy - Logarithmic Functions
- NumPy - Hyperbolic functions
- NumPy - Rounding functions
- NumPy Fourier Transforms
- NumPy - Discrete Fourier Transform (DFT)
- NumPy - Fast Fourier Transform (FFT)
- NumPy - Inverse Fourier Transform
- NumPy - Fourier Series and Transforms
- NumPy - Signal Processing Applications
- NumPy - Convolution
- NumPy Polynomials
- NumPy - Polynomial Representation
- NumPy - Polynomial Operations
- NumPy - Finding Roots of Polynomials
- NumPy - Evaluating Polynomials
- NumPy Statistics
- NumPy - Statistical Functions
- NumPy - Descriptive Statistics
- NumPy Datetime
- NumPy - Basics of Date and Time
- NumPy - Representing Date & Time
- NumPy - Date & Time Arithmetic
- NumPy - Indexing with Datetime
- NumPy - Time Zone Handling
- NumPy - Time Series Analysis
- NumPy - Working with Time Deltas
- NumPy - Handling Leap Seconds
- NumPy - Vectorized Operations with Datetimes
- NumPy ufunc
- NumPy - ufunc Introduction
- NumPy - Creating Universal Functions (ufunc)
- NumPy - Arithmetic Universal Function (ufunc)
- NumPy - Rounding Decimal ufunc
- NumPy - Logarithmic Universal Function (ufunc)
- NumPy - Summation Universal Function (ufunc)
- NumPy - Product Universal Function (ufunc)
- NumPy - Difference Universal Function (ufunc)
- NumPy - Finding LCM with ufunc
- NumPy - ufunc Finding GCD
- NumPy - ufunc Trigonometric
- NumPy - Hyperbolic ufunc
- NumPy - Set Operations ufunc
- NumPy Useful Resources
- NumPy Compiler
- NumPy - Quick Guide
- NumPy - Cheatsheet
- NumPy - Useful Resources
- NumPy - Discussion
NumPy - Matrix Addition
What is Matrix Addition?
Matrix addition is the operation where two matrices of the same size are added together. In matrix addition, each element in one matrix is added to the corresponding element in the other matrix.
For matrix addition to be possible, both matrices must have the same dimensions i.e., the same number of rows and columns.
If you have two matrices, say A and B, of the same size, then their sum C is defined as:
C = A + B
Where,
Cij = Aij + Bij
In other words, the element in the ith row and jth column of matrix C is the sum of the corresponding elements in matrices A and B.
Example of Matrix Addition
Consider the following two matrices:
A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]]
The sum C = A + B will be calculated as:
C = [[1+5, 2+6], [3+7, 4+8]] = [[6, 8], [10, 12]]
So, the result of adding matrices A and B gives us matrix C:
C = [[6, 8], [10, 12]]
Matrix Addition in NumPy
In NumPy, matrix addition is done using the + operator or using the numpy.add() function. NumPy arrays provide the ability to perform matrix operations element-wise, including addition, which is useful for performing fast mathematical computations.
Following are the key points to remember while performing matrix addition −
- Matrix Dimensions: For matrix addition to be valid, the matrices must have the same dimensions (same number of rows and columns).
- Element-wise Operations: NumPy automatically handles element-wise operations, making it very easy to add matrices using the + operator or the numpy.add() function.
- Flexible Arrays: NumPy arrays are flexible and can handle matrices of different sizes as long as they are compatible in dimensions.
Creating Matrices in NumPy
Before performing matrix addition, let us first create matrices in NumPy. Matrices in NumPy are essentially 2D arrays, and we can create them using the np.array() function as shown below −
import numpy as np # Creating two 2x2 matrices A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Print the matrices print("Matrix A:") print(A) print("\nMatrix B:") print(B)
Following is the output obtained −
Matrix A: [[1 2] [3 4]] Matrix B: [[5 6] [7 8]]
Matrix Addition Using the + Operator
The simplest way to add two matrices in NumPy is by using the + operator. This operator will automatically perform element-wise addition of the two matrices.
Example
In the following example, we are adding two matrices "A" and "B" using the "+" operator −
import numpy as np # Creating two 2x2 matrices A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Adding two matrices using the + operator C = A + B # Print the result print("Matrix C (A + B):") print(C)
The output obtained is as shown below −
Matrix C (A + B): [[ 6 8] [10 12]]
Using the numpy.add() Function
Alternatively, you can perform matrix addition using the numpy.add() function, which works the same way as the + operator. This function takes two matrices (or arrays) as inputs and returns their sum.
Example
In this example, we are adding two matrices "A" and "B" using the "numpy.add()" function −
import numpy as np # Creating two 2x2 matrices A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6], [7, 8]]) # Adding two matrices using numpy.add() function C = np.add(A, B) # Print the result print("Matrix C (A + B using numpy.add()):") print(C)
We get the output as shown below −
Matrix C (A + B using numpy.add()): [[ 6 8] [10 12]]
Broadcasting in Matrix Addition
While matrix addition requires matrices of the same shape, NumPy has a powerful feature called broadcasting that allows for element-wise operations between arrays of different shapes.
Broadcasting automatically adjusts the shapes of arrays to allow operations between them. However, for matrix addition specifically, both matrices must have the same shape.
Example
To give you a sense of how broadcasting works (though not directly applicable to matrix addition), here is an example of adding a scalar to a matrix −
import numpy as np # Create a 2x2 matrix A = np.array([[1, 2], [3, 4]]) # Add a scalar to the matrix using broadcasting B = A + 10 # Print the result print("Matrix A + 10:") print(B)
The result produced is as follows −
Matrix A + 10: [[11 12] [13 14]]
Error Handling in Matrix Addition
If you try to add two matrices with different shapes (i.e., different dimensions), NumPy will raise an error. This is an important point to watch for when performing matrix addition.
Example
Following is an example of mismatch dimension in NumPy while performing matrix addition −
import numpy as np # Create two matrices with different shapes A = np.array([[1, 2], [3, 4]]) B = np.array([[5, 6, 7]]) C = A + B print(C)
After executing the above code, we get the following output −
Traceback (most recent call last): File "/home/cg/root/6734345c5507a/main.py", line 6, in <module> C = A + B ValueError: operands could not be broadcast together with shapes (2,2) (1,3)
Applications of Matrix Addition
- Image Processing: Matrices represent images as pixel values. Matrix addition is used to manipulate images by adding brightness or adjusting pixel values.
- Data Analysis: In data science, matrices represent datasets. Matrix operations like addition help combine datasets or modify them.
- Linear Systems: Matrix addition is used to solve systems of linear equations by adding matrices that represent different coefficients.
- Computer Graphics: Matrix operations are central to 3D transformations, where matrix addition helps with transformations like translation.