[线性代数]矩阵乘法算法实现
程序员文章站
2022-07-12 14:11:08
...
作者 | zhonglihao |
算法名 | 矩阵乘法 Matrix Multiplication |
分类 | 线性代数 |
复杂度 | n^3 |
形式与数据结构 | C++实现 一维数组存储 |
特性 | 指针封装返回 |
具体参考出处 | 教科书 |
备注 |
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
#include "stdio.h"
void MatrixPrint(int* arr, int row, int col);
int* MatrixMul(int* arr_A, const int row_A, const int col_A, int* arr_B, const int row_B, const int col_B);
int _tmain(int argc, _TCHAR* argv[])
{
//统一使用一维数组实现
const int row_A = 3;
const int col_A = 3;
int Mat_A[row_A*col_A] = { 1, 1, 1, 2, 2, 2, 3, 3, 3 };
const int row_B = 3;
const int col_B = 4;
int Mat_B[row_B*col_B] = { 1,2,3,4, 0,1,1,0, 2,2,2,2 };
//打印相乘原始矩阵
MatrixPrint(Mat_A, row_A, col_A);
MatrixPrint(Mat_B, row_B, col_B);
//矩阵相乘返回数组指针
int* arr_C = MatrixMul(Mat_A, row_A, col_A, Mat_B, row_B, col_B);
MatrixPrint(arr_C, row_A, col_B);
system("Pause");
return 0;
}
//矩阵相乘方法
int* MatrixMul(int* arr_A, const int row_A, const int col_A, int* arr_B, const int row_B, const int col_B)
{
int row_scan, col_scan, mul_scan, sum; //mul_scan 行列各数独立相乘扫描
int* arr_C; //输出矩阵
int arr_C_len = row_A * col_B; //输出矩阵大小
//判定是否符合相乘法则
if (col_A != row_B) return NULL;
//分配输出数组长度
arr_C = (int*)malloc(arr_C_len*sizeof(int));
//矩阵相乘
for (row_scan = 0; row_scan < row_A; row_scan++)//矩阵A行循环
{
for (col_scan = 0; col_scan < col_B; col_scan++)//矩阵B列循环
{
for (mul_scan = 0,sum = 0; mul_scan < col_A; mul_scan++)//A列=B行各数独立相乘
{
sum += arr_A[row_scan * col_A + mul_scan] * arr_B[col_scan + mul_scan * col_B];
}
arr_C[row_scan * col_B + col_scan] = sum;
}
}
//返回指针
return arr_C;
}
//矩阵打印方法
void MatrixPrint(int* arr, const int row, const int col)
{
int len = row * col;
int i,col_count;
for (i = 0, col_count = 0; i < len; i++)
{
printf("%d\t", arr[i]);
//单换行
if (++col_count >= col)
{
printf("\n");
col_count = 0;
}
}
//跳空换行
printf("\n");
return;
}
上一篇: Python: 矩阵与线性代数运算
下一篇: 奇异值分解(SVD)