Search code examples
c++functionmatrix-multiplication

Library like function from scratch for matrix multiplication in C++


Here I am trying to write a library like function for the matrix multiplication. And this function should support all the datatype such as float, int, etc. that's why I have used Template here. But, I am having a difficult time passing 2d arrays to the function.

Q) void matrix_mul(T a[][2], T b[][2], T c[][2], ll p, ll q, ll r) how can I pass 2d arrays without any need to pass second parameter i.e., T a[][2]?

Q) I want to write these functions in another file and then import it into the main file, just like how we import standard libraries?

PS: I am new to the CPP. Kindly direct me to the resources if these questions have already been answered. TIA

template <class T>
void matrix_mul(T a[][2], T b[][2], T c[][2], ll p, ll q, ll r){
    for (ll i = 0; i < p; ++i)
        for (ll j = 0; j < q; ++j)
            for (ll k = 0; k < r; ++k)
                c[i][j] += a[i][k] * b[k][j];
}
int main(){
    io;
    ll p = 2, q = 2, r = 2;
    ll a[2][2] = {{1, 1}, {1, 1}};
    ll b[2][2] = {{1, 1}, {1, 1}};
    ll c[2][2] = {0};

    for (ll i = 0; i < p; ++i)
        for (ll j = 0; j < r; ++j)
            c[i][j] = 0;

    matrix_mul(a, b, c, p, q, r);

    for (ll i = 0; i < p; ++i){
        for (ll j = 0; j < r; ++j)
            cout << c[i][j] << "\t";
        cout << nl;
    }
    return 0;   
}

UPDATE: After giving C++ a read, I was able to come up with a working solution (find below).


Solution

  • This is how I solve the above problem-

    • Define template in a header file .
    • Import the above-mentioned header file in the main.cpp #include "mat.hpp".
    • Used vector representation to overcome size specification.

    I have posted a complete solution here https://github.com/ssp4all/Matrix-Multiplication-and-Transpose