# 复数矩阵乘法

2022/08/16 16:27

#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, 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;
complex<double> c[3][4];

complex<double> a[3][4] = {
{complex<double>(1.0, 1.0), complex<double>(2.0,-1.0), complex<double>(3.0,2.0), complex<double>(-2.0,1.0)},
{complex<double>(1.0,-1.0), complex<double>(5.0,-1.0), complex<double>(1.0,2.0), complex<double>( 3.0,0.0)},
{complex<double>(0.0,-3.0), complex<double>(4.0,-1.0), complex<double>(2.0,2.0), complex<double>(-1.0,2.0)}
};

complex<double> b[4][4] = {
{complex<double>(1.0,-1.0), complex<double>( 4.0,-1.0), complex<double>( 5.0,1.0), complex<double>(-2.0,1.0)},
{complex<double>( 3.0,2.0), complex<double>( 0.0, 1.0), complex<double>( 2.0,0.0), complex<double>(-1.0,5.0)},
{complex<double>(6.0,-3.0), complex<double>( 3.0, 2.0), complex<double>( 1.0,1.0), complex<double>( 2.0,-1.0)},
{complex<double>(2.0,-1.0), complex<double>(-3.0,-2.0),  complex<double>(-2.0,1.0), complex<double>( 1.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].real() <<" + "<<setw(-3)<<setiosflags(ios::left)<<a[i][j].imag()<<"j ";
cout <<endl;
}

cout <<"Matrix B:" <<endl;
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 4; ++j)
cout<<setw(3)<<setiosflags(ios::right)<<b[i][j].real()<<" + "<<setw(-3)<<setiosflags(ios::left)<<b[i][j].imag()<<"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].real()<<" + "<<setw(-3)<<setiosflags(ios::left)<<c[i][j].imag()<<"j ";
cout <<endl;
}

return 0;
}

0 评论
0 收藏
0