# 矩阵的抽象数据类型定义(mooc笔记)

#include<stdio.h>
#include<stdlib.h>
#define MAXR 100    //矩阵最大行数
#define MAXC 100    //矩阵最大列数

typedef int ElementType;
typedef struct matrix* Matrix;

struct matrix{	//存放一个矩阵并记录行数列数
int row;
int col;
ElementType Data[MAXC][MAXR];
};

Matrix Create(int M,int N); //返回一个M*N的矩阵
int GetMaxRow(Matrix A);    //返回矩阵A的总行数
int GetMaxCol(Matrix A);    //返回矩阵A的总列数
ElementType GetEntry(Matrix A,int i,int j); //返回矩阵A的第i行、第j列的元素
Matrix Multiply(Matrix A,Matrix B); //返回矩阵C=AB
void Print_Matrix(Matrix A);    //打印矩阵

int main(void){
Matrix A,B,C,D;
A = Create(3,3);
B = Create(3,3);
D = Multiply(A,B);
Print_Matrix(C);
Print_Matrix(D);
return 0;
}

Matrix Create(int M,int N){
Matrix Ma = (Matrix)malloc(sizeof(struct matrix));
Ma->row = M;
Ma->col = N;

for(int i = 0; i < M; i++)
for(int j = 0; j < N; j++)
scanf("%d",&Ma->Data[j][i]);	//一行一行写入数值

return Ma;
}

int GetMaxRow(Matrix A){
return A->row;
}

int GetMaxCol(Matrix A){
return A->col;
}

ElementType GetEntry(Matrix A,int i,int j){
return A->Data[j-1][i-1];   //先找列号，再找行号
}

if(A->row != B->row || A->col != B->col){
return NULL;
}
Matrix C = (Matrix)malloc(sizeof(struct matrix));
C->row = A->row;
C->col = A->col;

for(int i = 0; i < C->col; i++)
for(int j = 0; j < C->row; j++)
C->Data[i][j] = A->Data[i][j] + B->Data[i][j];

return C;
}

Matrix Multiply(Matrix A,Matrix B){
if(A->row != B->row || A->col != B->col){
printf("Multiply error!\n");
return NULL;
}
Matrix C = (Matrix)malloc(sizeof(struct matrix));
C->row = A->row;
C->col = B->col;

//模拟矩阵的乘法
for(int i = 0; i < C->row; i++){
for(int j = 0; j < C->col; j++){
int temp = 0;
for(int k = 0; k < A->col; k++){
temp += A->Data[k][i]*B->Data[j][k];
}
C->Data[j][i] = temp;
}
}
return C;
}

void Print_Matrix(Matrix A){
for(int i = 0; i < A->row; i++){
for(int j = 0; j < A->col; j++){
printf("%4d",A->Data[j][i]);
if(j == A->col - 1) printf("\n");
}
}
}


08-14 6246

08-20 1687
02-07 157
12-06 7481
07-09 9167
11-11 352
03-16 4496
12-20
03-16 1512
01-10 444
06-05
08-07 79
03-14 2681
05-08 145