# 实数矩阵乘法

2022/08/16 16:28

#include <iostream>
#include <cmath>
#include <complex>
#include <iomanip>

using namespace std;

//a, ma, na       矩阵 A[ma][na]
//b, mb, nb       矩阵 B[mb][nb]
//c, ma, nb       矩阵 C[ma][nb] = A[ma][na] * B[mb][nb]
template <class  T>    //模板声明T为类型参数
void MatrixMultiply(T a[], int ma, int na, T b[], int mb, int nb, T c[])

int i, j, k, u;
if (na != mb)
{
cout <<"Matrix cannot multiply" <<endl;
return;
}

for (i = 0; i < ma; ++i)
{
for (j = 0; j < nb; ++j)
{
u = i * nb + j;
#if 0
//            cout <<setw(3)<<setiosflags(ios::right)<<a[u].real() <<" + "<<setw(-3)<<setiosflags(ios::left)<<a[u].imag()<<"j ";
cout <<a[u].real() <<" + "<<a[u].imag()<<"j ";
#endif

c[u] = (T)0;
for (k = 0; k < mb; ++k)
c[u] += a[i * na  + k] * b[k * nb + j];
}
//cout<<endl;
}

return;
}

int main()
{
int i,j;
double c[3][4];

int *p = NULL;
cout<<"sizeof(p) = "<<sizeof(p)<<" "<<endl;

double a[3][4] = {
{1.0, 2.0, 3.0, -2.0},
{1.0, 5.0, 1.0,   3.0},
{0.0, 4.0, 2.0,  -1.0}
};

double b[4][4] = {
{1.0, 4.0, 5.0, -2.0},
{3.0, 0.0, 2.0, -1.0},
{6.0, 3.0, 1.0,   2.0},
{2.0,-3.0,-2.0,  -2.0}
};

cout <<"Matrix A:" <<endl;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 4; ++j)
cout <<setw(3)<<setiosflags(ios::right)<<a[i][j]<<" ";
cout <<endl;
}

cout <<"Matrix B:" <<endl;
for (i = 0; i < 4; ++i)
{
for (j = 0; j < 4; ++j)
cout<<setw(3)<<setiosflags(ios::right)<<b[i][j]<<" ";
cout <<endl;
}

MatrixMultiply(&a[0][0], 3, 4, &b[0][0], 4, 4, &c[0][0]);

cout <<"Matrix C = A * B :" <<endl;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 4; ++j)
cout<<setw(3)<<setiosflags(ios::right)<<c[i][j]<<" ";
cout <<endl;
}

return 0;
}

0 评论
0 收藏
0