Showing posts with label Matrix. Show all posts
Showing posts with label Matrix. Show all posts

Python Program to Subtract two Matrices.

Matrix subtraction is a fundamental operation in linear algebra and is often required in various scientific and computational applications. In this article, we'll explore how to subtract two matrices using Python programming.

In matrix subtraction, elements of one matrix are subtracted from their corresponding elements in another matrix of the same dimensions. The result is a new matrix with dimensions identical to the original matrices being subtracted. 

Quick Tip: Ensure matrices have the same dimensions for subtraction (m x n).

Matrix Subtraction Program in Python.

Step-by-step Algorithm:
  • Define two matrices A and B, each represented as nested lists in Python.
  • Create a new matrix to store the result of the subtraction.
  • Subtract corresponding elements of matrices A and B to obtain the elements of the resultant matrix.
  • Use nested loops to iterate through each element in the matrices and perform subtraction.

Python Code:

# Python code for matrix subtraction
def subtract_matrices(matrix_A, matrix_B):
    result_matrix = []
    for i in range(len(matrix_A)):
        row = []
        for j in range(len(matrix_A[0])):
            row.append(matrix_A[i][j] - matrix_B[i][j])
        result_matrix.append(row)
    return result_matrix

# Example usage
matrix_A = [[1, 2, 3],
            [4, 5, 6],
            [7, 8, 9]]

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

result = subtract_matrices(matrix_A, matrix_B)
print("Resultant Matrix after subtraction:")
for row in result:
    print(row)
Output:
Resultant Matrix after subtraction:
[-8, -6, -4]
[-2, 0, 2]
[4, 6, 8]
  • Time Complexity: O(m x n) where m is the number of rows and n is the number of columns.
  • Space Complexity: O(m x n) because we need extra space to store the resultant matrix.

Python Program to Add Two Matrices.

In Python programming, performing matrix operations holds importance in various computational tasks. Adding two matrices is a fundamental operation, often encountered in scientific computing, data analysis, and machine learning. Let's understand the efficient way to perform this operation in Python.

Addition of Two Matrix

Matrix Addition in Python.

Matrix addition is possible only when the matrices meet specific conditions related to their dimensions. For two matrices A and B to be added together (A + B = C), they must satisfy the following conditions:
  • Both matrices must have the same number of rows and columns.
  • If matrix A has dimensions m x n (m rows and n columns), matrix B must also have dimensions m x n.

Python Code for Adding Two Matrices.
# Python Code for Matrix Addition
def add_matrices(matrix1, matrix2):
    # Check if matrices have the same dimensions
    if len(matrix1) != len(matrix2) or len(matrix1[0]) != len(matrix2[0]):
        return "Matrices should have the same dimensions for addition"

    result = []
    for i in range(len(matrix1)):
        row = []
        for j in range(len(matrix1[0])):
            row.append(matrix1[i][j] + matrix2[i][j])
        result.append(row)
    return result

# Example matrices for addition
matrix_A = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

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

# Calling the function to add matrices
resultant_matrix = add_matrices(matrix_A, matrix_B)
print("Resultant Matrix after Addition:")
for row in resultant_matrix:
    print(row)
Output:
Resultant Matrix after Addition:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]

Explanation: The add_matrices() function takes two matrices as input parameters and checks if they have the same dimensions. If the matrices have the same dimensions, it iterates through corresponding elements of the matrices, performs element-wise addition, and constructs the resultant matrix.
  • Time Complexity: O(m x n)
  • Space Complexity: O(m x n)

Python Program to Print 2D Matrix.

Printing a 2D matrix in Python is a fundamental operation, often encountered in various data manipulation and algorithmic tasks. A 2D matrix, also known as a 2D array, represents data in a grid format consisting of rows and columns. Python offers several methods to effectively display and print a 2D matrix.

Let's explore different methods to print a 2D matrix in Python:

Method 1: Using Nested Loops.

One of the simplest ways to print a 2D matrix is by utilizing nested loops to iterate through rows and columns.

Python Code:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Using nested loops to print the matrix
for row in matrix:
    for element in row:
        print(element, end=" ")  
    print()  # Move to the next line after printing a row
Output:
1 2 3
4 5 6 
7 8 9 

Method 2: Using List Comprehension.

Python's list comprehension offers a concise way to print a 2D matrix.

Python Code:
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Using list comprehension to print the matrix
[print(*row) for row in matrix]
Output:
1 2 3
4 5 6 
7 8 9 

Method 3: Using NumPy Library.

The NumPy library provides powerful functionalities for handling multi-dimensional arrays, including 2D matrices.

Python Code:
import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

# Printing the NumPy matrix
print(matrix)
Output:
1 2 3
4 5 6 
7 8 9 

Program to Find Transpose of 2D Matrix.

What is the Transpose of a Matrix?

A Transpose of a Matrix is obtained by changing the rows of a matrix to columns and columns to rows. Swapping the values of rows and columns (arr[i][j] with arr[j][i]).

Example:

Find Transpose of Matrix
Transpose of a Matrix

We can transpose any given array simply by running two nested loops and swapping elements of position arr[i][j] with the element of position arr[j][i]


Below is the C++ Code Implementation:

//C++ Code to Transpose a Matrix
#include<bits/stdc++.h>
using namespace std;

//function to transpose matrix
void transpose(int arr[][3]){

    for(int i = 0; i < 3; i++){
        for(int j = i+1; j < 3; j++){
            swap(arr[i][j], arr[j][i]);
        }
    }
}

int main(){
    int arr[3][3] = {{2, 3, 6},
                     {1, 4, 1},
                     {9, 2, 5}};

    transpose(arr);

    cout<<"Transpose of given Matrix: "<<endl;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }    
    return 0;             
}
Output:
Transpose of given Matrix: 
2 1 9
3 4 2
6 1 5
  • Time Complexity: O(MxN) where M is the number of rows and N is the number of columns.
  • Space Complexity: O(1), no extra space is required to solve this problem.
Next:

Program for the Multiplication of Two 2D Matrix.

In this post, we are going to learn the process of multiplication of two 2D arrays and display the resulting array on screen. 

Example:

Multiplication of Two 2D Matrix
Multiplication of Matrices

Below are a few points to keep in mind before performing Matrix Multiplication:

  • Matrix multiplication is only possible when the number of columns of the first matrix should be equal to the number of rows of the second matrix. 
  • In matrix multiplication, the product of an m x k matrix and k x n matrix is an m x n matrix.
  • Matrix multiplication is not commutative in nature, it means the order multiplication of two matrices matters and can change our result.
  • Each entry in the resulting matrix is the dot product of row elements of the first matrix with column elements of the second matrix.

Below is C++ Code Implementation:

//Program to for Multiplication of 2D Array (Matrix)
#include<iostream>
using namespace std;

int main(){
    int arr1[50][50], arr2[50][50], prod[50][50] = {0};
    int row1, col1, row2, col2;
    //column of first matrix should be equal to row of second matrix
    do{
        cout<<"Enter number of rows and columns for first matrix: ";
        cin>>row1>>col1;

        cout<<"Enter number of rows and columns for second matrix: ";
        cin>>row2>>col2;
    }while(col1 != row2);
    
    //Taking input for first matrix
    cout<<"Enter the elements of first Array: "<<endl;
    for(int i = 0; i < row1; i++){
        for(int j = 0; j < col1; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr1[i][j];
        }
    }
    //Taking input for second matrix
    cout<<"Enter the elements of second Array: "<<endl;
    for(int i = 0; i < row2; i++){
        for(int j = 0; j < col2; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr2[i][j];
        }
    }
    //Multiplication of Matrix
    cout<<"The Multiplication of two Matrices: "<<endl;
    for(int i = 0; i < row1; i++){
        for(int j = 0; j < col2; j++){
            for(int k = 0; k < col1; k++){
                prod[i][j] = arr1[i][k] * arr2[k][j];
            }
        }
    }

    cout<<"Displaying Product of Two Matrix: "<<endl;
    for(int i = 0; i < row1; i++){
        for(int j = 0; j < col2; j++){
            cout<<prod[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}
Output:
Enter number of rows and columns for first matrix: 2 3
Enter number of rows and columns for second matrix: 3 2
Enter the elements of first Array: 
Enter element for position arr[0][0] = 1
Enter element for position arr[0][1] = 2
Enter element for position arr[0][2] = 3
Enter element for position arr[1][0] = 4
Enter element for position arr[1][1] = 5 
Enter element for position arr[1][2] = 6
Enter the elements of second Array: 
Enter element for position arr[0][0] = 6
Enter element for position arr[0][1] = 5
Enter element for position arr[1][0] = 4
Enter element for position arr[1][1] = 3
Enter element for position arr[2][0] = 2
Enter element for position arr[2][1] = 1
The Multiplication of two Matrices: 
6 3
12 6

In the above code, we have taken the first matrix of size 2 x 3 and the second matrix of size 3 x 2 and the resultant matrix that we get after multiplication is of size 2 x 2 which is satisfying our matrix property.

Next:

Program for the Addition of Two 2D Matrix.

In this post, we will learn how to add two (2D arrays) matrices and print them in the form of a single Matrix of the same size. Before moving directly to the program, let's first understand how this addition of two matrices happened and what the conditions record required for this operation. 

Note: A matrix can be used for addition or subtraction with another matrix only if both matrices have the same dimensions which means that both matrices should have an equal number of rows and the equal number of columns. (alert-success) 

Example: 

Addition of Two 2D Matrix.
Matrix Addition

Below is the C++ Code Implementation:
//C++ Program to for Addition of 2D Array (Matrix)
#include<iostream>
using namespace std;

int main(){
    int arr1[50][50], arr2[50][50], sum[50][50];
    int row, col;
    
    cout<<"Enter number of rows: ";
    cin>>row;

    cout<<"Enter number of column: ";
    cin>>col;
    //Taking input for first matrix
    cout<<"Enter the elements of first Array: "<<endl;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr1[i][j];
        }
    }
    //Taking input for second matrix
    cout<<"Enter the elements of second Array: "<<endl;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            cout<<"Enter element for position arr["<<i<<"]["<<j<<"] = ";
            cin>>arr2[i][j];
        }
    }
    
    //Addition of Matrix  
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            sum[i][j] = arr1[i][j] + arr2[i][j];
        }
    }

    cout<<"Displaying Sum of Two Matrix: "<<endl;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            cout<<sum[i][j]<<" ";
        }
        cout<<endl;
    }
    return 0;
}
Output:
Enter number of rows: 3
Enter number of column: 3
Enter the elements of first Array: 
Enter element for position arr[0][0] = 2
Enter element for position arr[0][1] = 3
Enter element for position arr[0][2] = 6
Enter element for position arr[1][0] = 1
Enter element for position arr[1][1] = 4
Enter element for position arr[1][2] = 1
Enter element for position arr[2][0] = 9
Enter element for position arr[2][1] = 2
Enter element for position arr[2][2] = 5
Enter the elements of second Array: 
Enter element for position arr[0][0] = 1
Enter element for position arr[0][1] = 2
Enter element for position arr[0][2] = 3
Enter element for position arr[1][0] = 4
Enter element for position arr[1][1] = 5
Enter element for position arr[1][2] = 6
Enter element for position arr[2][0] = 7
Enter element for position arr[2][1] = 8
Enter element for position arr[2][2] = 9
Displaying Sum of Two Matrix: 
3 5 9
5 9 7
16 10 14
In the above code, we have taken two 3x3 matrices for addition, and after adding we have stored our result in a sum matrix which is of the same 3x3 size. 

In the same way, you can write a program for the subtraction of two matrices, you just need to change the arithmetic operation from addition to subtraction and everything else will remain the same as it is.

Next:

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson