subtraction of a 2d matrix in c++
To subtract two 2D matrices in C++, you can follow the steps below:
Declare the matrices: Start by declaring two 2D matrices, let's call them
matrix1
andmatrix2
, of the same size. You can declare them as arrays of arrays or as vectors of vectors.Initialize the matrices: Assign values to the elements of both matrices. This can be done manually or using loops to iterate over the rows and columns of the matrices and assign values.
Create a result matrix: Declare another 2D matrix, let's call it
resultMatrix
, with the same size as the input matrices to store the result of the subtraction.Perform the subtraction: Use nested loops to iterate over the rows and columns of the input matrices. Subtract the corresponding elements of
matrix1
andmatrix2
and store the result in the corresponding position ofresultMatrix
. The subtraction can be done using the-
operator.Display the result: Finally, iterate over the rows and columns of
resultMatrix
and print the elements to display the resulting matrix.
Here's an example code snippet that demonstrates the subtraction of two 2D matrices:
#include <iostream>
#include <vector>
using namespace std;
int main() {
// Declare and initialize the input matrices
vector<vector<int>> matrix1 = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
vector<vector<int>> matrix2 = {{9, 8, 7},
{6, 5, 4},
{3, 2, 1}};
// Create a result matrix
vector<vector<int>> resultMatrix(matrix1.size(), vector<int>(matrix1[0].size()));
// Perform the subtraction
for (int i = 0; i < matrix1.size(); i++) {
for (int j = 0; j < matrix1[0].size(); j++) {
resultMatrix[i][j] = matrix1[i][j] - matrix2[i][j];
}
}
// Display the result
cout << "Result matrix:" << endl;
for (int i = 0; i < resultMatrix.size(); i++) {
for (int j = 0; j < resultMatrix[0].size(); j++) {
cout << resultMatrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
This code declares two matrices matrix1
and matrix2
, initializes them with values, subtracts them element-wise, and stores the result in resultMatrix
. Finally, it displays the resulting matrix resultMatrix
.