//时间复杂度O(xyz) 如果是方阵就是O(N^3)
#include <iostream>
using namespace std;
int ** matrix(int** marXY, int** marYZ,int x,int y,int z);
//数据结构作业,计算两个矩阵
int main(){
//开辟两个矩阵(指针型)
int** marXY = new int*[2];
int** marYZ = new int*[2];
for (int i = 0; i<2; i++) {
marXY[i] = new int[2];
}
for (int i = 0; i<3; i++) {
marYZ[i] = new int[3];
}
//因为矩阵相乘函数是传的指针数组,这里吧
int marXYcopy[2][2] = { {2,5},
{1,3}
};
int marYZcopy[2][3] = {
{4,2,3},
{1,3,1}
};
//把数值型矩阵 传给指针型矩阵
for (int i = 0; i<2; i++) {
for (int j = 0; j<2; j++) {
marXY[i][j] = marXYcopy[i][j];
}
}
for (int i = 0; i<2; i++) {
for (int j = 0; j<3; j++) {
marYZ[i][j] = marYZcopy[i][j];
}
}
int **rul = matrix(marXY, marYZ,2, 2, 3 );
for (int i = 0; i<2; i++) {
for (int j = 0; j<3; j++) {
cout <<rul[i][j]<<" ";
}
cout << endl;
}
delete rul;
return 0;
}
//marXY 矩阵x行y列
//marYZ 矩阵y行z列
int ** matrix(int** marXY, int** marYZ,int x,int y,int z){
//声明个二维数组
int** newMatrix = new int*[x];
for (int i = 0; i < y; i++) {
newMatrix[i] = new int[z];
}
//外层newMatrix的x坐标。
for (int i = 0 ; i < x; i++) {
//外层newMatrix的y坐标。
for (int j = 0; j < z; j++) {
int cur = 0;
for (int k = 0; k < y; k++) {
//将第i行 与 第 j列,按照内标的大小,依次相乘后相加。
cur += marXY[i][k]*marYZ[k][j];
}
//新数组的第ij位置的数
newMatrix[i][j] = cur;
}
}
return newMatrix;
}
计算两个矩阵相乘
最新推荐文章于 2025-02-17 12:12:14 发布