标签归档:矩阵

矩阵的乘法(C语言)

矩阵的乘法

只有矩阵1的列数等于矩阵2的行数时, 才有矩阵1与矩阵2的乘积.

当矩阵A[m,n] B[n, p]时: AB[m, p]
A矩阵为m行, n列
B矩阵为n行, p列

A与B的乘积AB则有m行, p列元素

矩阵的乘积, C代码

#include <stdio.h>

#define M 2
#define N 3
#define P 2

void mul(const int ma[M][N], const int mb[N][P], int mc[M][P]);

int main(void)
{
	int i, j;

	int ma[M][N] = {{1, 2, 3}, {4, 5, 6}};
	int mb[N][P] = {{5, 6}, {4, 5}, {3, 1}};
	int mc[M][P] = {{0}};

	mul(ma, mb, mc);

	for (i = 0; i < M; i++) {
		for (j = 0; j < P; j++)	
			printf("mc[%d][%d] = %d  ", i, j, mc[i][j]);
		putchar('\n');
	}

	return 0;
}

void mul(const int ma[M][N], const int mb[N][P], int mc[M][P])
{
	int i, j, k;

	for (i = 0; i < M; i++) {
		for (j = 0; j < P; j++) {
			mc[i][j] = 0;
			for (k = 0; k < N; k++)
				mc[i][j] += ma[i][k] * mb[k][j];
		}
	}

	return;
}