Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

Matrix multiplication C++ code

  1. User

    Assistant: User: Matrix multiplication C++ code Assistant:

  2. 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 dimensions 3x2. 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 multiplyMatrices performs the multiplication and returns the result.
    • The displayMatrix function prints out the matrix.
    • In the main function, we define two matrices and check if the multiplication is possible. If it is, we call multiplyMatrices to perform the operation and displayMatrix to print the result.