blazelott
blazelott

Reputation: 11

C++ Parallel Matrix Multiplication, incorrect calculations

Result of my multiplication is like

-842150451 -842150451 -842150451 -842150451   
-842150451 -842150451 -842150451 -842150451 
-842150451 -84215045 -842150451 -842150451
-842150451 -84215045 -842150451 -842150451 

And I don't understand why, can somebody help with this please?

#include <iostream>
#include <stdlib.h>
#include <omp.h>
#include <random>
using namespace std;

#define NUM_THREADS 2

double**        A;
double**        B;
double**        C;
double          t_Start;
double          t_Stop;
int             Am;
int             An;
int             Bm;
int             Bn;

void            Get_Matrix();
void            Mat_Mult_Parallel();


int main()
{
    cout << "Matrix A: ";
    cin >> Am >> An;
    cout << "Matrix B: ";
    cin >> Bm >> Bn;

    Get_Matrix();
    Mat_Mult_Parallel();


    system("pause");
    return 0;

}


void Get_Matrix()
{


    A = new double*[Am];
    B = new double*[Bm];
    C = new double*[Am];
    for (int i = 0; i<Am; i++) { A[i] = new double[An]; }
    for (int i = 0; i<Bm; i++) { B[i] = new double[Bn]; }
    for (int i = 0; i<Am; i++) { C[i] = new double[Bn]; }
    omp_set_num_threads(NUM_THREADS);
#pragma omp parallel for private(i,j) schedule(dynamic)
    for (int i = 0; i<Am; i++)
    {
        for (int j = 0; j<An; j++)
        {
            A[i][j] = rand() % 10 +1;
            cout << A[i][j] << " ";


        }
        cout << endl;
    }
    printf("\n");

#pragma omp parallel for private(i,j) schedule(dynamic)
    for (int i = 0; i<Bm; i++)
    {
        for (int j = 0; j<Bn; j++)
        {
            B[i][j] = rand() % 10 + 1;
            cout << B[i][j] << " ";


        }
        cout << endl;
    }
    printf("Matrix Created.\n");
}

void Mat_Mult_Parallel()
{
    int i, j, k;
    t_Start = omp_get_wtime();

    omp_set_num_threads(NUM_THREADS);
#pragma omp parallel for private(i,j) schedule(dynamic)
    for (i = 0; i<Am; i++)
    {
        for (j = 0; j<Bn; j++)
        {
            for (k = 0; k<An; k++)
            {
                C[i][j] += A[i][k] * B[k][j];

            }
            cout << C[i][j] << " ";
        }
        cout << endl;
    }

    t_Stop = omp_get_wtime() - t_Start;
    cout << "Parallel: " << t_Stop << " seconds." << endl;
}

Upvotes: 0

Views: 312

Answers (1)

Trantor
Trantor

Reputation: 766

You did not initialize your matrix C, but you use the '+=' operator, adding values to random inital values in matrix C. So you will need something like this first:

for ( int i = 0; i < Am; i++ )
{
    for ( int j = 0; j < Bn; j++ )
    {
        C[ i ][ j ] = 0.0;
    }
}

Alternatively, you can use memset/setmem C function (depending on your system), which can be quicker.

By the way, do not use 'cout' in parallelized loops, the results might be confusing.

Upvotes: 4

Related Questions