TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Program to Calculate The Addition of 2 Matrices

Program to Calculate The Addition of 2 Matrices on fibonacci, factorial, prime, armstrong, swap, reverse, search, sort, stack, queue, array, linkedlist, tree, graph etc.

<< Back to PROGRAM

Program to calculate the addition of 2 matrices

Explanation

In this program, we need to add two matrices and print the resulting matrix.

Matrix:

Matrix is a rectangular two-dimensional array of numbers arranged in rows and columns. A matrix with m rows and n columns can be called as m � n matrix. Individual entries in the matrix are called element and can be represented by aij which suggests that the element a is present in the ith row and jth column.

Program to calculate the addition of 2 matrices

Addition of two matrices:

Two matrices A and B can be added if and only if they have same dimensions that are, the same number of rows and columns. It is not possible to add a 2 � 3 matrix with a 3 � 2 matrix. Addition of two matrices can be performed by adding their corresponding elements as

(A + B)ij= Aij + Bij
Program to calculate the addition of 2 matrices

Addition of two matrices can be performed by looping through the first and second matrix. Add the corresponding elements of both matrices and store the result in the third matrix.

Algorithm

  1. Declare and initialize 2 two-dimensional arrays a and b.
  2. Calculate the number of rows and columns present in the array a (as dimensions of both the arrays are same) and store it in variables rows and cols respectively.
  3. Declare another array sum with the similar dimensions.
  4. Loop through the arrays a and b, add the corresponding elements
    e.g a11 + b11 = sum11
  5. Display the elements of array sum.

Solution

Python

#Initialize matrix a
a = [
        [1, 0, 1],
        [4, 5, 6],
        [1, 2, 3]
    ];
 
#Initialize matrix b
b = [
          [1, 1, 1],
          [2, 3, 1],
          [1, 5, 1]
     ];
 
#Calculates number of rows and columns present in given matrix
rows = len(a);
cols = len(a[0]);
 
#Array sum will hold the result and is initialized with zeroes.
sum = [[0]*rows for i in range(cols)];
 
#Performs addition of matrices a and b. Store the result in matrix sum
for i in range(0, rows):
    for j in range(0, cols):
        sum[i][j] = a[i][j] + b[i][j];
 
print("Addition of two matrices: ");
for i in range(0, rows):
    for j in range(0, cols):
        print(sum[i][j]),
    print("\n")

Output:

Addition of two matrices: 
2 1 2 

6 8 7 

2 7 4 

C

#include <stdio.h>
 
int main()
{
    int rows, cols;
        
    //Initialize matrix a
    int a[][3] = {
                    {1, 0, 1},
                    {4, 5, 6},
                    {1, 2, 3}
                };
    
    //Initialize matrix b
    int b[][3] = {
                      {1, 1, 1},
                      {2, 3, 1},
                      {1, 5, 1}
                 };
    
    //Calculates number of rows and columns present in given matrix
    rows = (sizeof(a)/sizeof(a[0]));
    cols = (sizeof(a)/sizeof(a[0][0]))/rows;
    
    //Array sum will hold the result
    int sum[rows][cols];
    
    //Performs addition of matrices a and b. Store the result in matrix sum
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
            sum[i][j] = a[i][j] + b[i][j];
        }
    }
    
    printf("Addition of two matrices: \n");
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < cols; j++){
           printf("%d ", sum[i][j]);
        }
        printf("\n");
    }
 
    return 0;
}

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4  

JAVA

public class SumMatrix
{
    public static void main(String[] args) {
        int rows, cols;
        
        //Initialize matrix a
          int a[][] = {
                          {1, 0, 1},
                          {4, 5, 6},
                          {1, 2, 3}
                       };
          
          //Initialize matrix b
          int b[][] = {
                          {1, 1, 1},
                          {2, 3, 1},
                          {1, 5, 1}
                     };
          
          //Calculates number of rows and columns present in given matrix
          rows = a.length;
        cols = a[0].length;
        
          //Array sum will hold the result
        int sum[][] = new int[rows][cols];
        
        //Performs addition of matrices a and b. Store the result in matrix sum
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                sum[i][j] = a[i][j] + b[i][j];
            }
        }
        
        System.out.println("Addition of two matrices: ");
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
               System.out.print(sum[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4

C#

 using System;
                    
public class SumMatrix
{
    public static void Main()
    {
        int rows, cols;
        
        //Initialize matrix a
          int[,] a = {
                          {1, 0, 1},
                          {4, 5, 6},
                          {1, 2, 3}
                     };
          
          //Initialize matrix b
          int[,] b = {
                          {1, 1, 1},
                          {2, 3, 1},
                          {1, 5, 1}
                    };
          
          //Calculates number of rows and columns present in given matrix
          rows = a.GetLength(0);
        cols = a.GetLength(1);
        
          //Array sum will hold the result
        int[,] sum = new int[rows, cols];
        
        //Performs addition of matrices a and b. Store the result in matrix sum
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
                sum[i, j] = a[i, j] + b[i, j];
            }
        }
        
        Console.WriteLine("Addition of two matrices: ");
        for(int i = 0; i < rows; i++){
            for(int j = 0; j < cols; j++){
               Console.Write(sum[i, j] + " ");
            }
            Console.WriteLine();
        }
    }
}

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4

PHP

<!DOCTYPE html>
<html>
<body>
<?php
//Initialize matrix a
$a = array(
            array(1, 0, 1),
            array(4, 5, 6),
            array(1, 2, 3)
          );
 
//Initialize matrix b
$b = array(
              array(1, 1, 1),
             array(2, 3, 1),
             array(1, 5, 1)
           );
 
//Calculates number of rows and columns present in given matrix
$rows = count($a);
$cols = count($a[0]);
 
//Array sum will hold the result and initialize it with 0
$sum = array_fill(0, $cols, array_fill(0, $rows, 0));
 
//Performs addition of matrices a and b. Store the result in matrix sum
for($i = 0; $i < $rows; $i++){
    for($j = 0; $j < $cols; $j++){
        $sum[$i][$j] = $a[$i][$j] + $b[$i][$j];
    }
}
 
print("Addition of two matrices: <br>");
for($i = 0; $i < $rows; $i++){
    for($j = 0; $j < $cols; $j++){
       print($sum[$i][$j] . " ");
    }
    print("<br>");
}  
?>
</body>
</html>

Output:

Addition of two matrices: 
2 1 2 
6 8 7 
2 7 4

Next Topic#




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf