C++矩阵乘法

    xiaoxiao2021-03-25  124

           用惯了数学库,有的时候有些基本的运算,像矩阵求逆,转置矩阵什么的,写起来突然感觉有些生疏了,这里算是对一些基本线性代数的复习。用C写矩阵乘法;

      注意点:

           (1)二维数组与二级指针的区别;

           (2)矩阵乘法的要点,新的结果矩阵的第i行第j列是矩阵A的第i行与矩阵B的第j列的乘积,这一点不熟悉,写程序就会有点吃力;对程序结构思路就会存在不清晰的地方;

           (3)有很多可以完善的地方,由于时间问题,先记于此;

    #include "stdafx.h" #include<iostream> #include<numeric> #include<vector> #include<functional> #include<algorithm> using namespace std; void MatrixMul(int MatrixA[2][2], int RowA, int ColA, int MatrixB[2][2], int RowB, int ColB, int Result[2][2]) { if (ColA != RowB) { cout << "error" << endl; return; } for (size_t i = 0; i < RowA; i++) for (size_t j = 0; j < ColB; j++) { int sum = 0; for (size_t k = 0; k < ColA; k++) { sum = sum + MatrixA[i][k] * MatrixB[k][j]; } Result[i][j] = sum; } } int _tmain(int argc, _TCHAR* argv[]) { int A[2][2]={{1,2},{3,7}}; int B[2][2] = { { 2,5 },{ 6,1 } }; int Result[2][2]; MatrixMul(A, 2, 2, B, 2, 2,Result); cout << "相乘以后的结果为:" << endl; for (size_t i = 0; i < 2; i++) { for (size_t j = 0; j < 2; j++) { cout << Result[i][j] << " "; } cout << endl; } while (true); return 0; }

           

    转载请注明原文地址: https://ju.6miu.com/read-14455.html

    最新回复(0)