/*====================== mpi_gather01.c ============================== Calculates the matrix-vector product of a 4x4 matrix A and 4x1 vector x, using 4 processes. Originally, each process stores a row of A and a single entry of x. This method uses all_gather operations to place a full copy of x in each process, which then performs the row-column inner-product operation on its data. ====================================================================*/ #include #include main( int argc, char** argv) { // MyPE: My logical process number // NumPE: Number of processes // i: loop index variable int MyPE, NumPE, i; // MyA: Single 1x4 row of 4x4 array A // MyX: Row entry of 4x1 column vector x // FullX: Full copy of x // ip: Inner product (result for row i) // product: Final vector result double MyA[4], MyX, FullX[4], ip, product[4]; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &MyPE); MPI_Comm_size(MPI_COMM_WORLD, &NumPE); // Assign myself a row of A and x for (i=0; i<4; i++) { MyA[i] = MyPE + 1 + 4 * i; } MyX = MyPE + 17; // We want every process to have a copy of x, so // we perform all_gather operations MPI_Allgather(&MyX, 1, MPI_DOUBLE, FullX, 1, MPI_DOUBLE, MPI_COMM_WORLD); // Now, each process creates inner product for ith row ip = 0.0; for (i=0; i<4; i++) { ip = ip + MyA[i]*FullX[i]; } // Finally, we gather all process' ip into master process MPI_Gather(&ip, 1, MPI_DOUBLE, product, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD); if (MyPE == 0) { printf("Matrix-vector product is:\n"); for (i=0; i<4; i++) { printf("%lf\n", product[i]); } } MPI_Finalize(); return 0; }