实现两个N*N矩阵的乘法,矩阵由一维数组表示。
先介绍一下矩阵的加法:
1 void Add(int rows, int cols)
2 {
3 for(int i= 0;i<rows;i++)
4 {
5 for(int j=0;j<cols;j++)
6 result[i][j]=mat1[i][j]+mat2[i][j];
7 }
8 }
若两个矩阵要做乘法运:只有在一个矩阵的行数与另一个矩阵的列数相同时,才能做两个矩阵的乘法。
如何得到矩阵的转置:
矩阵的转置也是一个矩阵,原始矩阵中的行转变为转置矩阵的列。例如,有下述一个3×3矩阵:
1 2 3 6 7 8 4 5 9
那么它的转置矩阵为:
1 6 4 2 7 5 3 8 9
让我们从程序员的角度仔细地考察一下这一现象。假设原始数组为M,转置矩阵为MT。那么M[1][0]=6,在转置矩阵中我们发现MT [0][1]=6。因此,我们能够得到程序化的结论:转置一个矩阵实际上就是对换下标变量。用技术术语讲:
下面是得到转置矩阵的C代码:
[cpp] view plaincopy
void show_transpose(float mat[][10],int row,int col)
{
int i,j;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
printf("%f\t",mat[j][i]);
printf("\n");
}
}
以上方法显示了矩阵的转置。
[cpp] view plaincopy
#include<iostream>
using namespace std;
#define size 2
int multi(int *a , int *b , int N)
{
int i , j , k , temp;
int *c = (int*)malloc(N * N * sizeof(int));
for(i = 0 ; i < N ; i++)
{
for(j = 0 ; j < N ; j++)
{
temp = i * N + j;
*(c + temp) = 0;
for(k = 0 ; k < N ; k++)
{
*(c + temp) += a[i * N + k] * b[k * N + j];
}
cout<<*(c + temp)<<" ";
}
}
return *c;
}
int main()
{
int a[size * size] = {2 , 1 , 4 , 3};
int b[size * size] = {1 , -1 , 3 , 2};
multi(a , b , size);
return 0;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有