user
user

Reputation: 158

Matrix multiplication function C++

I seem to have an issue with my matrix multiplication function.

When I run the program I just get an n x n matrix with all of the values the same, as some wired double value, e.g 21312e-2 Here is my function code:

void Multiply(int i, int j, double mat1[10][10], double mat2[10][10]) {


double mat3[10][10];
for (int r = 0; r < i; r++) {
    for (int c = 0; c < j; c++) {
        for (int in = 0; in < i; in++) {
            mat3[r][c] += mat1[r][in] * mat2[in][c];
        }
        cout << mat3[r][c] << "  ";
    }
    cout << "\n";
}

}

mat1 and mat 2 are read into the program in the main thread using the function read:

void read_matrix(int m, int n, double mat[10][10])
{
    int i, j;
    for (i = 0; i<m; ++i)
        for (j = 0; j<n; ++j)
            cin >> mat[i][j];
}

Edit:Main Code

int main()
{
    int i1, i2, j1, j2;
    double mat1[10][10], mat2[10][10], mat3[10][10];

    scanf_s("%d %d\n", &i1, &j1, mat1);


    read_matrix(i1, j1, mat1);

    scanf_s("%d %d\n", &i2, &j2, mat2);

    read_matrix(i2, j2, mat2);

    printf("%d x %d matrix\n", i1, j1);
    print_matrix(i1, j1, mat1);
    printf("\n%d x %d matrix\n", i2, j2);
    print_matrix(i2, j2, mat2);

    Multiply(i1, j2, mat1, mat2);
    system("pause");
    return 0;
}

Upvotes: 1

Views: 9359

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129314

You need to fill mat3 with a zero value before adding to it.

Simplest way is to use:

double mat3[10][10] = {};

Upvotes: 4

Related Questions