1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
#include <iostream> #include <vector> using namespace std; // Function to add two matrices vector<vector<int>> addMatrices(const vector<vector<int>>& mat1, const vector<vector<int>>& mat2) { int rows = mat1.size(); int cols = mat1[0].size(); vector<vector<int>> result(rows, vector<int>(cols)); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { result[i][j] = mat1[i][j] + mat2[i][j]; } } return result; } // Function to multiply two matrices vector<vector<int>> multiplyMatrices(const vector<vector<int>>& mat1, const vector<vector<int>>& mat2) { int rows1 = mat1.size(); int cols1 = mat1[0].size(); int rows2 = mat2.size(); int cols2 = mat2[0].size(); if (cols1 != rows2) { throw invalid_argument("Matrix dimensions do not match for multiplication."); } vector<vector<int>> result(rows1, vector<int>(cols2, 0)); for (int i = 0; i < rows1; ++i) { for (int j = 0; j < cols2; ++j) { for (int k = 0; k < cols1; ++k) { result[i][j] += mat1[i][k] * mat2[k][j]; } } } return result; } // Function to print a matrix void printMatrix(const vector<vector<int>>& mat) { for (const auto& row : mat) { for (int val : row) { cout << val << " "; } cout << endl; } } int main() { // Define two matrices vector<vector<int>> mat1 = { {1, 2}, {3, 4} }; vector<vector<int>> mat2 = { {5, 6}, {7, 8} }; // Add matrices vector<vector<int>> sum = addMatrices(mat1, mat2); cout << "Sum of matrices:" << endl; printMatrix(sum); // Multiply matrices try { vector<vector<int>> product = multiplyMatrices(mat1, mat2); cout << "Product of matrices:" << endl; printMatrix(product); } catch (const invalid_argument& e) { cerr << e.what() << endl; } return 0; } |
Explanation
- Matrix Addition (
addMatrices
):- Takes two matrices
mat1
andmat2
as input. - Assumes that both matrices have the same dimensions.
- Creates a result matrix with the same dimensions.
- Adds corresponding elements from both matrices to fill the result matrix.
- Takes two matrices
- Matrix Multiplication (
multiplyMatrices
):- Takes two matrices
mat1
andmat2
as input. - Checks if the number of columns in
mat1
matches the number of rows inmat2
for valid matrix multiplication. - Creates a result matrix with the appropriate dimensions (
rows1 x cols2
). - Performs matrix multiplication using the standard formula:
result[i][j] += mat1[i][k] * mat2[k][j]
.
- Takes two matrices
- Print Matrix (
printMatrix
):- Takes a matrix and prints its elements row by row.
- Main Function:
- Defines two matrices for demonstration.
- Calls
addMatrices
to compute their sum and prints the result. - Calls
multiplyMatrices
to compute their product and prints the result. If the matrices are not compatible for multiplication, it catches and prints an error message.