矩阵快速幂
矩阵快速幂
矩阵加法
只有同型矩阵才能进行加减法(即行数与列数都相同)
#include
#include
#include
#include
#include
#include
using namespace std;
#define MAX 105
int main(int argc, char const *argv[])
{
int A[MAX][MAX];
int B[MAX][MAX];
int ans[MAX][MAX];
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
memset(ans, 0, sizeof(ans));
int line, row;
cin >> line >> row;
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
cin >> A[i][j];
}
}
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
cin >> B[i][j];
}
}
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
ans[i][j] = A[i][j] + B[i][j];
}
}
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
cout << ans[i][j] << " ";
}
cout << endl;
}}
矩阵减法
#include
#include
#include
#include
#include
#include
using namespace std;
#define MAX 105
int main(int argc, char const *argv[])
{
int A[MAX][MAX];
int B[MAX][MAX];
int ans[MAX][MAX];
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
memset(ans, 0, sizeof(ans));
int line, row;
cin >> line >> row;
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
cin >> A[i][j];
}
}
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
cin >> B[i][j];
}
}
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
ans[i][j] = A[i][j] - B[i][j];
}
}
for(int i = 1;
i <= line;
++i){
for(int j = 1;
j <= row;
++j){
cout << ans[i][j] << " ";
}
cout << endl;
}}
矩阵乘法
两个矩阵可以相乘的条件:第一个矩阵的列数必须等于第二个矩阵的行数
第一个矩阵:n * m第二个矩阵:m * r(可以运算)
第一个矩阵:n * m第二个矩阵:s * r(不可以运算)
#include
#include
#include
#include
#include
#include
using namespace std;
#define MAX 105
int main(int argc, char const *argv[])
{
int A[MAX][MAX];
int B[MAX][MAX];
int ans[MAX][MAX];
memset(A, 0, sizeof(A));
memset(B, 0, sizeof(B));
memset(ans, 0, sizeof(ans));
//初始化各矩阵
int a_line, a_row, b_line, b_row;
cin >> a_line >> a_row;
for(int i = 1;
i <= a_line;
++i){
for(int j = 1;
j <= a_row;
++j){
cin >> A[i][j];
}
}
cin >> b_line >> b_row;
for(int i = 1;
i <= b_line;
++i){
for(int j = 1;
j <= b_row;
++j){
cin >> B[i][j];
}
}
if(a_row != b_line){//第一个列数不等于第二个行数,不能进行运算
printf("Error: %d != %d\n", a_row, b_line);
}
else{
for(int i = 1;
i <= a_line;
++i){
for(int j = 1;
j <= b_row;
++j){
for(int k = 1;
k <= a_row;
++k){
ans[i][j] += A[i][k] * B[k][j];
}
}
}
cout << a_line << " " << b_row << endl;
for(int i = 1;
i <= a_line;
++i){
for(int j = 1;
j <= b_row;
++j){
if(j != b_row)
cout << ans[i][j] << " ";
else
cout << ans[i][j];
}
cout << endl;
}
}
}
【矩阵运算】