兩個二為矩陣的相乘,矩陣元素為浮點數,
Input 為 M1.txt M2.txt
Ouput 為 Output.txt
文字檔格式為
row
column
elements
例如2x3的矩陣:
2
3
1 2 3
4 5 6
=====結構與函式定義=====
// Matrix Structure
typedef struct MATRIX
{
int row;
int column;
float **data;
}MAT;
// M3 = M1 * M2
MAT M1, M2, M3;
void Init(MAT &mat);
void Multiply(const MAT mat1, const MAT mat2, MAT &mat3);
void Clear();
=====Main.cpp=====
#include "matrix.h"
#include <stdio.h>
#define FtoI // Float to Integer
int main(int argc, char **argv)
{
freopen("M1.txt","r",stdin);
scanf("%d", &M1.row);
scanf("%d", &M1.column);
Init(M1);
freopen("M2.txt","r",stdin);
scanf("%d", &M2.row);
scanf("%d", &M2.column);
Init(M2);
freopen("Output.txt","w",stdout);
Multiply(M1, M2, M3);
Clear();
return 0;
}
// Allocate memory space to matrix structure
void Init(MAT &mat)
{
mat.data = new float*[mat.row];
for(int i=0; i<mat.row; i++)
mat.data[i] = new float[mat.column];
for(int i=0;i<mat.row;i++)
for(int j=0;j<mat.column;j++)
{
float temp;
scanf("%f", &temp);
mat.data[i][j] = temp;
}
}
// M3 = M1 * M2
void Multiply(const MAT mat1, const MAT mat2, MAT &mat3)
{
if(mat1.column == mat2.row)
{
mat3.row = mat1.row;
mat3.column = mat2.column;
mat3.data = new float*[mat3.row];
for(int i=0; i<mat3.row; i++)
mat3.data[i] = new float[mat3.column];
// Multiply
for(int k=0; k<mat2.column; k++)
for(int i=0; i<mat1.row; i++)
{
mat3.data[i][k] = 0; // Set M3 to zero
for(int j=0; j<mat2.row; j++)
mat3.data[i][k] += mat1.data[i][j] * mat2.data[j][k];
}
printf("%d\n%d\n", mat3.row, mat3.column);
for(int i=0;i<mat3.row;i++)
{
for(int j=0;j<mat3.column;j++)
#ifdef FtoI
printf("%d\t", (int)mat3.data[i][j]);
#else
printf("%f\t", mat3.data[i][j]);
#endif
printf("\n");
}
}
else
printf("Dimentions error.\n");
}
// Release the memory space
void Clear()
{
delete M1.data;
delete M2.data;
delete M3.data;
}