Skip to content

Instantly share code, notes, and snippets.

@jacquerie
Created November 19, 2013 10:49
Show Gist options
  • Save jacquerie/7543619 to your computer and use it in GitHub Desktop.
Save jacquerie/7543619 to your computer and use it in GitHub Desktop.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#define ROOT 0
int main (int argc, char** argv) {
int i, j, rank, size;
MPI_Datatype diagonal;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Create the diagonal datatype
MPI_Type_vector(size, 1, size + 1, MPI_INT, &diagonal);
MPI_Type_commit(&diagonal);
// Allocate the matrix
int A[size][size];
// Fill it with the appropriate values
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
A[i][j] = (i == j) * rank;
}
}
// Gather all diagonals in the ROOT
MPI_Gather(A, 1, diagonal, A, size, MPI_INT, ROOT, MPI_COMM_WORLD);
// Print the matrix
if (rank == ROOT) {
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
printf("%d\t", A[i][j]);
}
printf("\n");
}
}
MPI_Type_free(&diagonal);
MPI_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment