C語言實現任意複數矩陣相乘

這裏借鑑了TI官方的dsp函數庫中的矩陣處理函數

void mat_mul_cplx(const float *x1, int r1, int c1, const float *x2,
	int c2, float *y)
{
	float real, imag;
	int i, j, k;

	for (i = 0; i < r1; i++)
	for (j = 0; j < c2; j++)
	{
		real = 0;
		imag = 0;

		for (k = 0; k < c1; k++)
		{
			real += (x1[i * 2 * c1 + 2 * k] * x2[k * 2 * c2 + 2 * j]
				- x1[i * 2 * c1 + 2 * k + 1] * x2[k * 2 * c2 + 2 * j + 1]);
			imag += (x1[i * 2 * c1 + 2 * k] * x2[k * 2 * c2 + 2 * j + 1]
				+ x1[i * 2 * c1 + 2 * k + 1] * x2[k * 2 * c2 + 2 * j]);
		}

		y[i * 2 * c2 + 2 * j] = real;
		y[i * 2 * c2 + 2 * j + 1] = imag;
	}
}

測試程序如下(矩陣A爲3*1階 矩陣B爲1*3階):

int main()
{
	int i;
	float A[6] = {1.2,2.1,3.0,4.2,5.0,6.0};
	float B[6] = {1.2,2.1, 3.0,4.2,5.0,6.0 };
	float C[18];
	mat_mul_cplx(A, 3, 1, B, 3, C);
	for (i = 0; i < 18; i++)
	{
		cout << C[i]<<endl;
	}
}

結果如下:

matlab計算結果如下:

兩者結果一致。 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章