Open In App

Program for subtraction of matrices

Last Updated : 01 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two m x n matrices m1 and m2, the task is to subtract m2 from m1 and return res.

Input: m1 = {{1, 2},
{3, 4}},
m2 = {{4, 3},
{2, 1}}
Output: {{-3, -1},
{1, 3}}

Input: m1 = {{3, 3, 3},
{3, 3, 3}},
m1 = {{2, 2, 2},
{1, 1, 1}},
Output: {{1, 1, 1},
{2, 2, 2}},

We traverse both matrices element by element and subtract m2[i][j] from m1[i][j].

C++
#include <iostream>
#include <vector>
using namespace std;

// This function subtracts m2 from m1 and
// stores the result in res
void subtract(vector<vector<int>>& m1, 
              vector<vector<int>>& m2, 
              vector<vector<int>>& res) 
{
    int rows = m1.size();
    int cols = m1[0].size();
    
    for (int i = 0; i < rows; i++)
        for (int j = 0; j < cols; j++)
            res[i][j] = m1[i][j] - m2[i][j];
}

// Driver code
int main() 
{
    // Define two rectangular matrices
    vector<vector<int>> m1 = { {1, 2, 3}, 
                                {4, 5, 6} };
    vector<vector<int>> m2 = { {1, 1, 1}, 
                                {1, 1, 1} };
    
    // Result matrix with the same dimensions
    vector<vector<int>> res(m1.size(), vector<int>(m1[0].size()));

    // Perform the subtraction
    subtract(m1, m2, res);

    // Print the result matrix
    cout << "Result matrix is:" << endl;
    for (auto& row : res) 
    {
        for (int val : row) 
            cout << val << " ";
        cout << endl;
    }

    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

#define R 2 // Number of rows
#define C 3 // Number of columns

// This function subtracts m2 from m1 and
// stores the result in res
void subtract(int m1[R][C], int m2[R][C], int res[R][C]) {
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++)
            res[i][j] = m1[i][j] - m2[i][j];
}

// Driver code
int main() {
  
    // Define two rectangular matrices
    int m1[R][C] = { {1, 2, 3}, 
                     {4, 5, 6} };
    int m2[R][C] = { {1, 1, 1}, 
                     {1, 1, 1} };
    
    // Result matrix with the same dimensions
    int res[R][C];

    // Perform the subtraction
    subtract(m1, m2, res);

    // Print the result matrix
    printf("Result matrix is:\n");
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++)
            printf("%d ", res[i][j]);
        printf("\n");
    }

    return 0;
}
Java
// This function subtracts m2 from m1 and
// stores the result in res
public class MatrixSubtraction {
    public static void subtract(int[][] m1, int[][] m2, int[][] res) {
        int rows = m1.length;
        int cols = m1[0].length;
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                res[i][j] = m1[i][j] - m2[i][j];
    }

    public static void main(String[] args) {
        // Define two rectangular matrices
        int[][] m1 = { {1, 2, 3}, {4, 5, 6} };
        int[][] m2 = { {1, 1, 1}, {1, 1, 1} };

        // Result matrix with the same dimensions
        int[][] res = new int[m1.length][m1[0].length];

        // Perform the subtraction
        subtract(m1, m2, res);

        // Print the result matrix
        System.out.println("Result matrix is:");
        for (int[] row : res) {
            for (int val : row) 
                System.out.print(val + " ");
            System.out.println();
        }
    }
}
Python
# This function subtracts m2 from m1 and
# stores the result in res
def subtract(m1, m2):
    rows = len(m1)
    cols = len(m1[0])
    res = [[0] * cols for _ in range(rows)]
    for i in range(rows):
        for j in range(cols):
            res[i][j] = m1[i][j] - m2[i][j]
    return res

# Driver code
if __name__ == '__main__':
  
    # Define two rectangular matrices
    m1 = [[1, 2, 3], [4, 5, 6]]
    m2 = [[1, 1, 1], [1, 1, 1]]

    # Perform the subtraction
    res = subtract(m1, m2)

    # Print the result matrix
    print("Result matrix is:")
    for row in res:
        print(' '.join(map(str, row)))
C#
using System;
using System.Collections.Generic;

class Program {
    // This function subtracts m2 from m1 and
    // stores the result in res
    static void Subtract(int[,] m1, int[,] m2, int[,] res) {
        int rows = m1.GetLength(0);
        int cols = m1.GetLength(1);
        
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                res[i, j] = m1[i, j] - m2[i, j];
    }

    // Driver code
    static void Main() {
        // Define two rectangular matrices
        int[,] m1 = { {1, 2, 3}, 
                       {4, 5, 6} };
        int[,] m2 = { {1, 1, 1}, 
                       {1, 1, 1} };
        
        // Result matrix with the same dimensions
        int[,] res = new int[m1.GetLength(0), m1.GetLength(1)];

        // Perform the subtraction
        Subtract(m1, m2, res);

        // Print the result matrix
        Console.WriteLine("Result matrix is:");
        for (int i = 0; i < res.GetLength(0); i++) {
            for (int j = 0; j < res.GetLength(1); j++)
                Console.Write(res[i, j] + " ");
            Console.WriteLine();
        }
    }
}
JavaScript
// This function subtracts m2 from m1 and
function subtract(m1, m2) {
    const rows = m1.length;
    const cols = m1[0].length;
    const res = Array.from({ length: rows }, () => Array(cols).fill(0));
    for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
            res[i][j] = m1[i][j] - m2[i][j];
        }
    }
    return res;
}

// Driver code
const m1 = [[1, 2, 3], [4, 5, 6]];
const m2 = [[1, 1, 1], [1, 1, 1]];

// Perform the subtraction
const res = subtract(m1, m2);

// Print the result matrix
console.log('Result matrix is:');
res.forEach(row => {
    console.log(row.join(' '));
});
PHP
<?php
// This function subtracts m2 from m1 and
// stores the result in res
function subtract($m1, $m2) {
    $rows = count($m1);
    $cols = count($m1[0]);
    $res = array();
    
    for ($i = 0; $i < $rows; $i++) {
        for ($j = 0; $j < $cols; $j++) {
            $res[$i][$j] = $m1[$i][$j] - $m2[$i][$j];
        }
    }
    return $res;
}

// Driver code
$m1 = array(array(1, 2, 3), 
            array(4, 5, 6));
$m2 = array(array(1, 1, 1), 
            array(1, 1, 1));

// Perform the subtraction
$res = subtract($m1, $m2);

// Print the result matrix
echo "Result matrix is:\n";
foreach ($res as $row) {
    echo implode(' ', $row) . "\n";
}
?>

Output
Result matrix is:
0 1 2 
3 4 5 

Time complexity: O(n2)


Next Article
Practice Tags :

Similar Reads