Skip to main content

Two Matrix Addition

Matrix addition is a fundamental operation in linear algebra, which is widely used in various fields including mathematics, engineering, computer graphics, and data analysis. It involves adding corresponding elements of two matrices to produce a new matrix. This operation is based on the principle that the matrices being added must have the same dimensions.

Problem Statement

Given two matrices A and B of size ROW x COL, the task is to perform matrix addition and obtain a new matrix C, where each element c[i][j] is the sum of the corresponding elements from matrices A and B, i.e., c[i][j] = a[i][j] + b[i][j].

Description

Matrix addition is an important operation that combines the elements of two matrices to create a third matrix. Let's take a closer look at how matrix addition works with an example.

Consider two matrices: Matrix A:

1  2  3
-6  1  2
5  4  3

Matrix B:

3  1  4
1  7  3
2  2  2

Matrix addition involves adding the corresponding elements of the matrices:

(1+3)  (2+1)  (3+4)
(-6+1) (1+7)  (2+3)
(5+2)  (4+2)  (3+2)

This results in the following matrix:

4  3  7
-5  8  5
7  6  5

Idea to Solve the Problem

The problem can be solved by following these steps:

  1. Define two matrices A and B with the same dimensions (ROW x COL).
  2. Iterate through each element of the matrices and calculate the sum of the corresponding elements.
  3. Store the sum in a new matrix C of the same dimensions.
  4. Display the matrices A, B, and C to showcase the inputs and the result of the addition.

Pseudocode

Here's the pseudocode to perform matrix addition:

function matrixAddition(matrix1, matrix2):
    initialize result matrix of the same dimensions as matrix1 and matrix2

    for i from 0 to ROW - 1:
        for j from 0 to COL - 1:
            result[i][j] = matrix1[i][j] + matrix2[i][j]

    display "Matrix A:"
    display matrix1
    display "Matrix B:"
    display matrix2
    display "Matrix A + Matrix B:"
    display result

Algorithm Explanation

  1. The function matrixAddition takes two matrices matrix1 and matrix2 as input and initializes a new matrix result of the same dimensions.
  2. It then iterates through each element using two nested loops, where i represents the row index and j represents the column index.
  3. For each element, it calculates the sum of the corresponding elements from matrix1 and matrix2 and stores it in the corresponding position of the result matrix.
  4. After calculating the entire result matrix, the function displays the original matrices matrix1 and matrix2, and then displays the result matrix result.

Code Solution

/*
  C Program 
+ Perform two matrix addition
*/
#include <stdio.h>

#define ROW 3
#define COL 3

//Display the element of given 2d matrix
void show_data(int matrix[][COL]) {
  
  printf("-----------------\n");
  
  for (int i = 0; i < ROW; ++i) {

    for (int j = 0; j < COL; ++j) {

      printf("%4d", matrix[i][j]);
    }

    printf("\n");
  }

  printf("\n");
}
void addition(int matrix1[][COL],int matrix2[][COL])
{

  //This matrix are store the result of addition 
  int result[ROW][COL];

  for (int i = 0; i < ROW; ++i) {

    for (int j = 0; j < COL; ++j) {

      //Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
      result[i][j] = matrix1[i][j] + matrix2[i][j];
      
    }
  }
  //Display Matrix Elements
  printf("  Matrix A\n");
  //print element of matrix1
  show_data(matrix1);


  printf("\n  Matrix B\n");
  //print element of matrix1
  show_data(matrix2);


  printf("\n (Matrix A) + \n (Matrix B)\n");
  //Display resultant matrix
  show_data(result);

}
int main() {
  //Define matrix 1
  int matrix1[ROW][COL] = {
    {
      1, 2, 3
    },

    {
      -6, 1, 2
    },
    {
      5, 4, 3
    }
  };

   //Define matrix 2
  int matrix2[ROW][COL] = {
    {
      3, 1, 4
    },
    {
      1, 7, 3
    },
    {
      2, 2, 2
    }
  };

  addition(matrix1,matrix2);
  
  return 0;
}

Output

  Matrix A
-----------------
   1   2   3
  -6   1   2
   5   4   3


  Matrix B
-----------------
   3   1   4
   1   7   3
   2   2   2


 (Matrix A) +
 (Matrix B)
-----------------
   4   3   7
  -5   8   5
   7   6   5
/*
 C++ Program
 Perform two matrix addition
*/
#include<iostream>
using namespace std;
#define ROW 3
#define COL 3
class MyMatrix {
	public:

		//Display the element of given 2d matrix
		void show_data(int matrix[ROW][COL]) {
			cout << "-----------------\n";
			//Assume  N x N Matrix size
			for (int i = 0; i < ROW; ++i) {
				for (int j = 0; j < COL; ++j) {
					cout << " " << matrix[i][j];
				}
				cout << "\n";
			}
			cout << "\n";
		}
	void addition(int matrix1[ROW][COL], int matrix2[ROW][COL]) {
		//Assume both matrix are equal size
		//Assume  N x N Matrix size
		

	   //This matrix are store the result of addition 
		int result[ROW][COL];
		for (int i = 0; i < ROW; ++i) {
			for (int j = 0; j < COL; ++j) {
				//Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
				result[i][j] = matrix1[i][j] + matrix2[i][j];
			}
		}
		cout << " Matrix A\n";
		//print element of matrix1
		this->show_data(matrix1);
		cout << "\n Matrix B\n";
		//print element of matrix1
		this->show_data(matrix2);
		cout << "\n (Matrix A) + \n (Matrix B)\n";
		//Display resultant matrix
		this->show_data(result);
	}
};
int main() {
	MyMatrix obj;
  	//Define matrix 1
	int matrix1[ROW][COL] = {
			{
				1,
				2,
				3
			},
			{
				-6,
				1,
				2
			},
			{
				5,
				4,
				3
			}
		};
	//Define matrix 2
	int matrix2[ROW][COL] = {
			{
				3,
				1,
				4
			},
			{
				1,
				7,
				3
			},
			{
				2,
				2,
				2
			}
		};
	obj.addition(matrix1, matrix2);
	return 0;
}

Output

 Matrix A
-----------------
 1 2 3
 -6 1 2
 5 4 3


 Matrix B
-----------------
 3 1 4
 1 7 3
 2 2 2


 (Matrix A) +
 (Matrix B)
-----------------
 4 3 7
 -5 8 5
 7 6 5
/*
  Java Program
  Perform two matrix addition
*/
public class MyMatrix {
 
  //Display the element of given 2d matrix
  public void show_data(int [][]matrix) {
    
    System.out.print("-----------------\n");
    
    //Assume  N x N Matrix size
    int row = matrix.length;

    int col = matrix[0].length;

    for (int i = 0; i < row; ++i) {

      for (int j = 0; j < col; ++j) {

        System.out.print("  "+ matrix[i][j]);
      }

      System.out.print("\n");
    }

    System.out.print("\n");
  }
  public void addition(int [][]matrix1,int [][]matrix2)
  {
    //Assume both matrix are equal size
    //Assume  N x N Matrix size
    int row = matrix1.length;

    int col = matrix1[0].length;

    //This matrix are store the result of addition 
    int [][]result = new int[row][col];

    for (int i = 0; i < row; ++i) {

      for (int j = 0; j < col; ++j) {

        //Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
        result[i][j] = matrix1[i][j] + matrix2[i][j];
        
      }
    }
    System.out.print("  Matrix A\n");
    //print element of matrix1
    show_data(matrix1);


    System.out.print("\n  Matrix B\n");
    //print element of matrix1
    show_data(matrix2);


    System.out.print("\n (Matrix A) + \n (Matrix B)\n");
    //Display resultant matrix
    show_data(result);

  }

  public static void main(String[] args) {

    MyMatrix obj = new MyMatrix();
    //Define matrix 1
    int [][]matrix1 = {
      {
        1, 2, 3
      },

      {
        -6, 1, 2
      },
      {
        5, 4, 3
      }
    };


     //Define matrix 2
    int [][]matrix2 = {
      {
        3, 1, 4
      },
      {
        1, 7, 3
      },
      {
        2, 2, 2
      }
    };
    obj.addition(matrix1,matrix2);

  }
}

Output

 Matrix A
-----------------
 1 2 3
 -6 1 2
 5 4 3


 Matrix B
-----------------
 3 1 4
 1 7 3
 2 2 2


 (Matrix A) +
 (Matrix B)
-----------------
 4 3 7
 -5 8 5
 7 6 5
/*
  C# Program
  Perform two matrix addition
*/
using System;
public class MyMatrix {

	//Display the element of given 2d matrix
	public void show_data(int[,] matrix) {

		Console.Write("-----------------\n");

		//Assume  N x N Matrix size
		int row = matrix.GetLength(0);

		int col = matrix.GetLength(1);

		for (int i = 0; i < row; ++i) {

			for (int j = 0; j < col; ++j) {

				Console.Write("  " + matrix[i,j]);
			}

			Console.Write("\n");
		}

		Console.Write("\n");
	}
	public void addition(int[,] matrix1, int[,] matrix2) {
		//Assume both matrix are equal size
		//Assume  N x N Matrix size
		int row = matrix1.GetLength(0);

		int col = matrix1.GetLength(1);

		//This matrix are store the result of addition 
		int[,] result = new int[row,col];

		for (int i = 0; i < row; ++i) {

			for (int j = 0; j < col; ++j) {

				//Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
				result[i,j] = matrix1[i,j] + matrix2[i,j];

			}
		}
		Console.Write("  Matrix A\n");
		//print element of matrix1
		show_data(matrix1);


		Console.Write("\n  Matrix B\n");
		//print element of matrix1
		show_data(matrix2);


		Console.Write("\n (Matrix A) + \n (Matrix B)\n");
		//Display resultant matrix
		show_data(result);

	}

	public static void Main(String[] args) {

		MyMatrix obj = new MyMatrix();
		//Define matrix 1
		int[,] matrix1 = {
			{
				1,
				2,
				3
			},

			{
				-6,
				1,
				2
			},
			{
				5,
				4,
				3
			}
		};


		//Define matrix 2
		int[,] matrix2 = {
			{
				3,
				1,
				4
			},
			{
				1,
				7,
				3
			},
			{
				2,
				2,
				2
			}
		};
		obj.addition(matrix1, matrix2);

	}
}

Output

  Matrix A
-----------------
  1  2  3
  -6  1  2
  5  4  3


  Matrix B
-----------------
  3  1  4
  1  7  3
  2  2  2


 (Matrix A) +
 (Matrix B)
-----------------
  4  3  7
  -5  8  5
  7  6  5
<?php
/*
  Php Program
  Perform two matrix addition
*/
class MyMatrix {
	//Display the element of given 2d matrix

	public 	function show_data($matrix) {
		echo("-----------------\n");
		//Assume  N x N Matrix size
		$row = count($matrix);
		$col = count($matrix[0]);
		for ($i = 0; $i < $row; ++$i) {
			for ($j = 0; $j < $col; ++$j) {
				echo(" ". $matrix[$i][$j]);
			}
			echo("\n");
		}
		echo("\n");
	}
	public 	function addition($matrix1, $matrix2) {
		//Assume both matrix are equal size
		//Assume  N x N Matrix size
		$row = count($matrix1);
		$col = count($matrix1[0]);
		//This matrix are store the result of addition 
		$result = array_fill(0, $row,array_fill(0,$row,0));
		for ($i = 0; $i < $row; ++$i) {
			for ($j = 0; $j < $col; ++$j) {
				//Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
				$result[$i][$j] = $matrix1[$i][$j] + $matrix2[$i][$j];
			}
		}
		echo(" Matrix A\n");
		//print element of matrix1
		$this->show_data($matrix1);
		echo("\n Matrix B\n");
		//print element of matrix1
		$this->show_data($matrix2);
		echo("\n (Matrix A) + \n (Matrix B)\n");
		//Display resultant matrix
		$this->show_data($result);
	}
};

function main() {
	$obj = new MyMatrix();
	//Define matrix 1
	$matrix1 = array(array(1, 2, 3), array(-6, 1, 2), array(5, 4, 3));
	//Define matrix 2
	$matrix2 = array(array(3, 1, 4), array(1, 7, 3), array(2, 2, 2));
	$obj->addition($matrix1, $matrix2);
}
main();

Output

 Matrix A
-----------------
 1 2 3
 -6 1 2
 5 4 3


 Matrix B
-----------------
 3 1 4
 1 7 3
 2 2 2


 (Matrix A) +
 (Matrix B)
-----------------
 4 3 7
 -5 8 5
 7 6 5
/*
 Node Js Program
 Perform two matrix addition
*/
class MyMatrix {
	//Display the element of given 2d matrix
	show_data(matrix) {
		process.stdout.write("-----------------\n");
		//Assume  N x N Matrix size
		var row = matrix.length;
		var col = matrix[0].length;
		for (var i = 0; i < row; ++i) {
			for (var j = 0; j < col; ++j) {
				process.stdout.write(" " + matrix[i][j]);
			}
			process.stdout.write("\n");
		}
		process.stdout.write("\n");
	}
	addition(matrix1, matrix2) {
		//Assume both matrix are equal size
		//Assume  N x N Matrix size
		var row = matrix1.length;
		var col = matrix1[0].length;
		//This matrix are store the result of addition 
		var result = Array(row).fill(0).map(() => new Array(col).fill(0));
		for (var i = 0; i < row; ++i) {
			for (var j = 0; j < col; ++j) {
				//Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
				result[i][j] = matrix1[i][j] + matrix2[i][j];
			}
		}
		process.stdout.write(" Matrix A\n");
		//print element of matrix1
		this.show_data(matrix1);
		process.stdout.write("\n Matrix B\n");
		//print element of matrix1
		this.show_data(matrix2);
		process.stdout.write("\n (Matrix A) + \n (Matrix B)\n");
		//Display resultant matrix
		this.show_data(result);
	}
}

function main(args) {
	var obj = new MyMatrix();
	//Define matrix 1
	var matrix1 = [
		[1, 2, 3],
		[-6, 1, 2],
		[5, 4, 3]
	];
	//Define matrix 2
	var matrix2 = [
		[3, 1, 4],
		[1, 7, 3],
		[2, 2, 2]
	];
	obj.addition(matrix1, matrix2)
}
main();

Output

 Matrix A
-----------------
 1 2 3
 -6 1 2
 5 4 3


 Matrix B
-----------------
 3 1 4
 1 7 3
 2 2 2


 (Matrix A) +
 (Matrix B)
-----------------
 4 3 7
 -5 8 5
 7 6 5
# Python 3 Program

# Perform two matrix addition
class MyMatrix :
  # Display the element of given 2d matrix
  def show_data(self, matrix) :
    print("-----------------")
    row = len(matrix)
    col = len(matrix[0])
    i = 0
    while (i < row) :
      j = 0
      while (j < col) :
        print(" ", matrix[i][j],end="")
        j += 1
      
      print(end="\n")
      i += 1
    
    print("\n")
  
  def addition(self, matrix1, matrix2) :
    # Assume both matrix are equal size
    # Assume  N x N Matrix size
    row = len(matrix1)
    col = len(matrix1[0])
    result = [[0 for i in range(col)] for j in range(row)] 
    i = 0
    while (i < row) :
      j = 0
      while (j < col) :
        # Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
        result[i][j] = matrix1[i][j] + matrix2[i][j]
        j += 1
      
      i += 1
    
    print(" Matrix A")
    self.show_data(matrix1)
    print(" Matrix B")
    self.show_data(matrix2)
    print(" (Matrix A) + \n (Matrix B)")
    self.show_data(result)
  

def main() :
  obj = MyMatrix()
  matrix1 = [
    [1, 2, 3],
    [-6, 1, 2],
    [5, 4, 3]
  ]
  matrix2 = [
    [3, 1, 4],
    [1, 7, 3],
    [2, 2, 2]
  ]
  obj.addition(matrix1, matrix2)


if __name__ == "__main__":
  main()

Output

 Matrix A
-----------------
  1  2  3
  -6  1  2
  5  4  3


 Matrix B
-----------------
  3  1  4
  1  7  3
  2  2  2


 (Matrix A) + 
 (Matrix B)
-----------------
  4  3  7
  -5  8  5
  7  6  5
# Ruby Program 
# Perform two matrix addition
class MyMatrix 
	# Display the element of given 2d matrix
	def show_data(matrix) 
		print("-----------------\n")
		row = matrix.length
		col = matrix[0].length
		i = 0
		while (i < row) 
			j = 0
			while (j < col) 
				print(" ", matrix[i][j])
				j += 1
			end
			print("\n")
			i += 1
		end
		print("\n")
	end
	def addition(matrix1, matrix2) 
		# Assume both matrix are equal size
		# Assume  N x N Matrix size
		row = matrix1.length
		col = matrix1[0].length
		result = Array.new(row){ Array.new(col, 0) }
		i = 0
		while (i < row) 
			j = 0
			while (j < col) 
				# Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
				result[i][j] = matrix1[i][j] + matrix2[i][j]
				j += 1
			end
			i += 1
		end
		print(" Matrix A\n")
		self.show_data(matrix1)
		print("\n Matrix B\n")
		self.show_data(matrix2)
		print("\n (Matrix A) + \n (Matrix B)\n")
		self.show_data(result)
	end
end
def main() 
	obj = MyMatrix.new()
	matrix1 = [
		[1, 2, 3],
		[-6, 1, 2],
		[5, 4, 3]
	]
	matrix2 = [
		[3, 1, 4],
		[1, 7, 3],
		[2, 2, 2]
	]
	obj.addition(matrix1, matrix2)
end
main()

Output

 Matrix A
-----------------
 1 2 3
 -6 1 2
 5 4 3


 Matrix B
-----------------
 3 1 4
 1 7 3
 2 2 2


 (Matrix A) + 
 (Matrix B)
-----------------
 4 3 7
 -5 8 5
 7 6 5

/*
 Scala Program
 Perform two matrix addition
*/
class MyMatrix {
	//Display the element of given 2d matrix
	def show_data(matrix: Array[Array[Int]]): Unit = {
		print("-----------------\n");
		var row: Int = matrix.length;
		var col: Int = matrix(0).length;
		var i: Int = 0;
		while (i < row) {
			var j: Int = 0;
			while (j < col) {
				print(" " + matrix(i)(j));
				j += 1;
			}
			print("\n");
			i += 1;
		}
		print("\n");
	}
	def addition(matrix1: Array[Array[Int]], matrix2: Array[Array[Int]]): Unit = {
		//Assume both matrix are equal size
		//Assume  N x N Matrix size
		var row: Int = matrix1.length;
		var col: Int = matrix1(0).length;
		var result: Array[Array[Int]] = Array.fill[Int](row,col)(0);
		var i: Int = 0;
		while (i < row) {
			var j: Int = 0;
			while (j < col) {
				//Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
				result(i)(j) = matrix1(i)(j) + matrix2(i)(j);
				j += 1;
			}
			i += 1;
		}
		print(" Matrix A\n");
        this.show_data(matrix1);
        print("\n Matrix B\n");
        this.show_data(matrix2);
        print("\n (Matrix A) + \n (Matrix B)\n");
        this.show_data(result);
	}
}
object Main {
	def main(args: Array[String]): Unit = {
		var obj: MyMatrix = new MyMatrix();
		var matrix1: Array[Array[Int]] = Array(
			Array(1, 2, 3),
			Array(-6, 1, 2),
			Array(5, 4, 3));
		var matrix2: Array[Array[Int]] = Array(
			Array(3, 1, 4),
			Array(1, 7, 3),
			Array(2, 2, 2));
  		obj.addition(matrix1, matrix2);
	}
}

Output

 Matrix A
-----------------
 1 2 3
 -6 1 2
 5 4 3


 Matrix B
-----------------
 3 1 4
 1 7 3
 2 2 2


 (Matrix A) +
 (Matrix B)
-----------------
 4 3 7
 -5 8 5
 7 6 5
/*
  Swift 4 Program
  Perform two matrix addition
*/
class MyMatrix {
	//Display the element of given 2d matrix
	func show_data(_ matrix: [
		[Int]
	]) {
		print("-----------------");
		let row: Int = matrix.count;
		let col: Int = matrix[0].count;
		var i: Int = 0;
		while (i < row) {
			var j: Int = 0;
			while (j < col) {
				print(" ", matrix[i][j],terminator:"");
				j += 1;
			}
			print(terminator:"\n");
			i += 1;
		}
		print("\n");
	}
	func addition(_ matrix1: [
		[Int]
	], _ matrix2: [
		[Int]
	]) {
		//Assume both matrix are equal size
		//Assume  N x N Matrix size
		let row: Int = matrix1.count;
		let col: Int = matrix1[0].count;
		var result: [[Int]] = Array(repeating : Array( repeating:0 , count:col) ,  count:row);
	
		var i: Int = 0;
		while (i < row) {
			var j: Int = 0;
			while (j < col) {
				//Add matrix A [i] row and [j] columns to the Matrix B [j] columns and [i] rows
				result[i][j] = matrix1[i][j] + matrix2[i][j];
				j += 1;
			}
			i += 1;
		}
		print(" Matrix A");
		self.show_data(matrix1);
		print("\n Matrix B");
		self.show_data(matrix2);
		print("\n (Matrix A) + \n (Matrix B)");
		self.show_data(result);
	}
}
func main() {
	let obj: MyMatrix = MyMatrix();
	let matrix1: [
		[Int]
	] = [
		[1, 2, 3],
		[-6, 1, 2],
		[5, 4, 3]
	];
	let matrix2: [
		[Int]
	] = [
		[3, 1, 4],
		[1, 7, 3],
		[2, 2, 2]
	];
	obj.addition(matrix1, matrix2);
}
main();

Output

 Matrix A
-----------------
  1  2  3
  -6  1  2
  5  4  3



 Matrix B
-----------------
  3  1  4
  1  7  3
  2  2  2



 (Matrix A) +
 (Matrix B)
-----------------
  4  3  7
  -5  8  5
  7  6  5

Time Complexity

The time complexity of this code is determined by the nested loops used to iterate through the matrices. Since the matrices have dimensions ROW x COL, there are ROW * COL elements to process.

Therefore, the time complexity is O(ROW * COL), where ROW and COL are the number of rows and columns in the matrices, respectively.





Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment