我很长时间以来一直坚持这个程序,所以基本上我必须在p x p笛卡尔网格上乘以2 n x n矩阵,p< = n(n可以被p整除)
在您的程序中,2D网格的过程0应该读取矩阵A和B. 从文件。示例:
<矩阵维数n>
<矩阵A>
<矩阵B>
4
-11.0 -12.0 6.0 9.0
-11.0 12.0 2.0 4.0
8.0 6.0 12.0 11.0
6.0 4.0 -10.0 1.0
2.0 11.0 1.0 7.0
3.0 1.0 -2.0 4.0
1.0 9.0 11.0 3.0
6.0 1.0 -1.0 5.0
我能够使用进程0将矩阵读入两个数组A和B,但我需要对程序的其余部分提供一些帮助。
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
int p, rank, k, n;
float *A = NULL, *B=NULL;
char filename[FILENAME_MAX];
//MPI_Status status;
FILE *file;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &p );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
// asks for filename
if ( rank == 0 ) {
printf("p=%d", p);
printf("Enter filename: ");
scanf("%s", filename);
// file is opened
file = fopen(filename, "r");
fscanf( file, "%d", &n );
printf( "\nMatrix size = %d\n", n );
// As per the expected format of the file the size of the matrix comes first in the file
}
// broadcasts the value of n to all the processes
MPI_Bcast( &n, 1, MPI_INT, 0, MPI_COMM_WORLD );
if ( n*n > p )
{
// since p perfectly divides the n x n matrixes assumed
if ( rank == 0 )
{
printf( "No. of processes must be at least %d\n", n*n );
fclose( file );
}
MPI_Finalize( );
exit( 1 );
}
// Read and print input data matrix A and B
if ( rank == 0 )
{
A = (float *) malloc( n*n*sizeof(float) );
printf( "\nMatrix A:\n" );
for ( k=0;k<n*n; k++ )
{
fscanf( file, "%f", &A[k] );
printf( "%7.1f", A[k] );
if ( (k+1)%n == 0 ) printf( "\n" );
}
// reads matrix B
B = (float *) malloc( n*n*sizeof(float) );
printf( "\nMatrix B:\n" );
for ( k=0;k<n*n; k++ )
{
fscanf( file, "%f", &B[k] );
printf( "%7.1f", B[k] );
if ( (k+1)%n == 0 ) printf( "\n" );
} fclose( file );
}
MPI_Finalize( ); return 0;
}