两个矩阵可以相乘,必须满足的条件是:左边矩阵的列等于右边矩阵的行
如:一个3x4的矩阵和一个4x2的矩阵相乘,得到一个3x2的矩阵;
矩阵乘法函数:
mat3 add(mat1 A,mat2 B){
mat3 ans;
for(int i=0;i<s1;i++)
for(int j=0;j<s2;j++){ //A矩阵和B矩阵相乘,结果返回一个ans矩阵。
ans.c[i][j]=0;
for(int k=0;k<s3;k++) //s1:A矩阵的行,s2:B矩阵的列。(ans的行,列)
ans.c[i][j]+=A.a[i][k]*B.b[k][j]; //s3: A矩阵的列,B矩阵的行(他俩相等)
}
return ans;
}
下面举一个简单的栗子:
就是图中的那俩矩阵相乘:
#include<bits/stdc++.h>
using namespace std;
struct mat1{
int a[3][4];
};
struct mat2{
int b[4][2];
};
struct mat3{
int c[3][2];
};
mat3 add(mat1 A,mat2 B){
mat3 ans;
for(int i=0;i<3;i++)
for(int j=0;j<2;j++){
ans.c[i][j]=0;
for(int k=0;k<4;k++)
ans.c[i][j]+=A.a[i][k]*B.b[k][j];
}
return ans;
}
int main(){
mat1 x34;
mat2 y42;
mat3 z32;
int i,j;
for(i=0;i<3;i++){
for(j=0;j<4;j++){
cin>>x34.a[i][j];
}
}
for(i=0;i<4;i++){
for(j=0;j<2;j++){
cin>>y42.b[i][j];
}
}
z32=add(x34,y42);
for(i=0;i<3;i++){
for(j=0;j<2;j++){
cout<<z32.c[i][j]<<" " ;
}
cout<<endl;
}
return 0;
}
结果;:;
例题 :问题 1472: [蓝桥杯][基础练习VIP]矩阵乘法
给定一个N阶矩阵A,输出A的M次幂(M是非负整数)
例如:
A =
1 2
3 4
A的2次幂
7 10
15 22
输入
第一行是一个正整数N、M(1< =N< =30, 0< =M< =5),表示矩阵A的阶数和要求的幂数
接下来N行,每行N个绝对值不超过10的非负整数,描述矩阵A的值
输出
输出共N行,每行N个整数,表示A的M次幂所对应的矩阵。相邻的数之间用一个空格隔开
样例输入
2 2 1 2 3 4
样例输出
7 10 15 22
#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
typedef unsigned long long ll;
struct mix{
ll a[32][32];
};
mix M_pow(mix jichu,mix ce,int x){
mix ans;
for(int i=0;i<x;i++){
for(int j=0;j<x;j++){
ans.a[i][j]=0;
for(int k=0;k<x;k++)
ans.a[i][j]+=jichu.a[i][k]*ce.a[k][j];
}
}
return ans;
}
int main(){
int a,b;
mix final,ce;
cin>>a>>b;
ll t;
for(int i=0;i<a;i++){
for(int j=0;j<a;j++){
cin>>final.a[i][j];
ce.a[i][j]=final.a[i][j];
}
}
if(b){
int n=b-1;
while(n--){
final=M_pow(final,ce,a);
}
for(int i=0;i<a;i++){
for(int j=0;j<a;j++){
if(j!=a-1)
cout<<final.a[i][j]<<" ";
else
{
cout<<final.a[i][j]<<endl; /* code */
}
}
}
}
else {
for(int i=0;i<a;i++){
for(int j=0;j<a;j++){
if(i==j){
cout<<1;
}
else{
cout<<0;
}
if(j!=a-1)
cout<<" ";
else{
cout<<endl;
}
}
}
}
system("pause");
return 0;
}