I tried to send the second and third column of a matrix from the processes with rank one and two with MPI to the process with rank zero.
On the internet I found this example http://www.mcs.anl.gov/research/projects/mpi/mpi-standard/mpi-report-1.1/node70.htm#Figure4 and wrote a code:
#include <iostream>
#include <mpi.h>
using namespace std;
int main(int argc, char *argv[]) {
int id;
int matrix[3][3];
int matrixB[9];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
if(id == 0)
matrix[i][j] = 0;
else
matrix[i][j] = j+1;
MPI_Datatype matrixSpalte;
MPI_Type_vector(3, 1, 3, MPI_INT, &matrixSpalte);
MPI_Type_commit(&matrixSpalte);
MPI_Gather(&matrix[0][id], 1, matrixSpalte, &matrixB[0], 1, matrixSpalte, 0, MPI_COMM_WORLD);
if(id == 0)
for(int i=0; i<9; i++) {
if(i % 3 == 0)
cout << endl;
cout << matrixB[i] << " (" << i << ") ";
}
MPI_Finalize();
return 0;
}
but the output is:
0 (0) 0 (1) 1351992736 (2)
0 (3) 254423040 (4) 1 (5)
0 (6) 2 (7) 1351992752 (8)
It should be:
1 (0) 2 (1) 3 (2)
1 (3) 2 (4) 3 (5)
1 (6) 2 (7) 3 (8)
and I have not idea why this isn't working. I hope someone can help me to find the mistake in my code.
Your sincerely,
Heinz
Solution (thx to Jonathan Dursi):
#include <iostream>
#include <mpi.h>
using namespace std;
int main(int argc, char *argv[]) {
int id;
int matrix[3][3];
int matrixB[9];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &id);
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
if(id == 0)
matrix[i][j] = 0;
else
matrix[i][j] = j+1;
MPI_Datatype matrixSpalte, tmp;
MPI_Type_vector(3, 1, 3, MPI_INT, &tmp);
MPI_Type_create_resized(tmp, 0, sizeof(int), &matrixSpalte); // !!!
MPI_Type_commit(&matrixSpalte);
MPI_Gather(&matrix[0][id], 1, matrixSpalte, matrixB, 1, matrixSpalte, 0, MPI_COMM_WORLD);
if(id == 0)
for(int i=0; i<9; i++) {
if(i % 3 == 0)
cout << endl;
cout << matrixB[i] << " (" << i << ") ";
}
MPI_Finalize();
return 0;
}