gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Matrix multiplication C++ code
- User
Assistant: User: Matrix multiplication C++ code Assistant:
- Assistant
Certainly! Here is a simple C++ code for performing matrix multiplication. This program multiplies two matrices and stores the result in a third matrix.
#include <iostream> #include <vector> using namespace std; // Function to multiply two matrices vector<vector<int>> multiplyMatrices(const vector<vector<int>>& A, const vector<vector<int>>& B) { int n = A.size(); int m = B[0].size(); int p = A[0].size(); vector<vector<int>> C(n, vector<int>(m, 0)); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { for (int k = 0; k < p; ++k) { C[i][j] += A[i][k] * B[k][j]; } } } return C; } // Function to display a matrix void displayMatrix(const vector<vector<int>>& matrix) { for (const auto& row : matrix) { for (const auto& element : row) { cout << element << " "; } cout << endl; } } int main() { // Sample matrices vector<vector<int>> A = {{1, 2, 3}, {4, 5, 6}}; vector<vector<int>> B = {{7, 8}, {9, 10}, {11, 12}}; // Check if multiplication is possible if (A[0].size() != B.size()) { cout << "Matrix multiplication not possible due to incompatible dimensions." << endl; return -1; } // Multiply the matrices vector<vector<int>> C = multiplyMatrices(A, B); // Display the result cout << "Resultant matrix:" << endl; displayMatrix(C); return 0; }Explanation:
- Matrix A has dimensions
2x3, and Matrix B has dimensions3x2. For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. - The function
multiplyMatricesperforms the multiplication and returns the result. - The
displayMatrixfunction prints out the matrix. - In the
mainfunction, we define two matrices and check if the multiplication is possible. If it is, we callmultiplyMatricesto perform the operation anddisplayMatrixto print the result.
- Matrix A has dimensions