-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmatrixvector.c
More file actions
80 lines (71 loc) · 1.66 KB
/
matrixvector.c
File metadata and controls
80 lines (71 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <mpi.h>
#define NCOLS 6
int main(int argc, char **argv) {
int i,j,k,l;
int ierr, rank, size, root;
float A[NCOLS],A_exact[NCOLS],Apart[NCOLS];
float Bpart[NCOLS],B[NCOLS][NCOLS];
float C[NCOLS],Cpart[1];
root = 0;
/* Initiate MPI. */
ierr=MPI_Init(&argc, &argv);
ierr=MPI_Comm_rank(MPI_COMM_WORLD, &rank);
ierr=MPI_Comm_size(MPI_COMM_WORLD, &size);
/* Initialize B and C. */
if (rank == root) {
B[0][0] = 1;
B[0][1] = 2;
B[0][2] = 3;
B[0][3] = 4;
B[1][0] = 4;
B[1][1] = -5;
B[1][2] = 6;
B[1][3] = 4;
B[2][0] = 7;
B[2][1] = 8;
B[2][2] = 9;
B[2][3] = 2;
B[3][0] = 3;
B[3][1] = -1;
B[3][2] = 5;
B[3][3] = 0;
C[0] = 1;
C[1] = -4;
C[2] = 7;
C[3] = 3;
}
/* Put up a barrier until I/O is complete */
ierr=MPI_Barrier(MPI_COMM_WORLD);
/* Scatter matrix B by rows. */
ierr=MPI_Scatter(B,NCOLS,MPI_FLOAT,Bpart,NCOLS,
MPI_FLOAT,root, MPI_COMM_WORLD);
/* Scatter matrix C by columns */
ierr=MPI_Scatter(C, 1, MPI_FLOAT, Cpart, 1, MPI_FLOAT,
root,MPI_COMM_WORLD);
/* Do the vector-scalar multiplication. */
for(j=0;j<NCOLS;j++)
Apart[j] = Cpart[0]*Bpart[j];
/* Reduce to matrix A. */
ierr=MPI_Reduce(Apart,A,NCOLS,MPI_FLOAT,
MPI_SUM, root, MPI_COMM_WORLD);
if (rank == 0) {
printf("\nThis is the result of the parallel computation:\n\n");
printf("A[0]=%g\n",A[0]);
printf("A[1]=%g\n",A[1]);
printf("A[2]=%g\n",A[2]);
printf("A[3]=%g\n",A[3]);
for(k=0;k<NCOLS;k++) {
A_exact[k] = 0.0;
for(l=0;l<NCOLS;l++) {
A_exact[k] += C[l]*B[l][k];
}
}
printf("\nThis is the result of the serial computation:\n\n");
printf("A_exact[0]=%g\n",A_exact[0]);
printf("A_exact[1]=%g\n",A_exact[1]);
printf("A_exact[2]=%g\n",A_exact[2]);
printf("A_exact[3]=%g\n",A_exact[3]);
}
MPI_Finalize();
}