fork download
  1. #include <mpi.h>
  2. #include <stdio.h>
  3.  
  4. int main(int argc, char** argv) {
  5. MPI_Init(&argc, &argv);
  6.  
  7. int rank, size;
  8. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  9. MPI_Comm_size(MPI_COMM_WORLD, &size);
  10.  
  11. // Assumptions based on problem: 7 ranks, each with part of the data
  12. const int rows_per_rank = 25; // Each rank handles 25 rows
  13. const int total_columns = 100; // Total columns in the matrix
  14. float apart[rows_per_rank][total_columns]; // Partial matrix on each rank
  15. float b[total_columns]; // Vector for multiplication
  16. float cpart[rows_per_rank]; // Partial result on each rank
  17. float ctotal[rows_per_rank * size]; // Final result (gathered from all ranks)
  18.  
  19. // Initialize the matrix 'apart' and vector 'b' with some values
  20. // For example, here we fill them with 1s to simplify.
  21. for (int i = 0; i < rows_per_rank; i++) {
  22. for (int k = 0; k < total_columns; k++) {
  23. apart[i][k] = 1.0f; // Example value, could be anything
  24. }
  25. }
  26.  
  27. // Initialize vector 'b' with 1s (again, as an example)
  28. for (int k = 0; k < total_columns; k++) {
  29. b[k] = 1.0f;
  30. }
  31.  
  32. // Each rank calculates its part of the matrix-vector product
  33. for (int i = 0; i < rows_per_rank; i++) {
  34. cpart[i] = 0.0f;
  35. for (int k = 0; k < total_columns; k++) {
  36. cpart[i] += apart[i][k] * b[k];
  37. }
  38. }
  39.  
  40. // Use MPI_Allgather to gather the partial results from all ranks into 'ctotal'
  41. MPI_Allgather(cpart, rows_per_rank, MPI_FLOAT,
  42. ctotal, rows_per_rank, MPI_FLOAT,
  43. MPI_COMM_WORLD);
  44.  
  45.  
  46. // For demonstration, let's print the results on rank 0
  47. if (rank == 0) {
  48. printf("Final result vector (gathered from all ranks):\n");
  49. for (int i = 0; i < rows_per_rank * size; i++) {
  50. printf("%f ", ctotal[i]);
  51. }
  52. printf("\n");
  53. }
  54.  
  55. MPI_Finalize();
  56. return 0;
  57. }
  58.  
Success #stdin #stdout #stderr 0.26s 40536KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected symbol in "void MPI_MyAllgather"
Execution halted