行列乗算アルゴリズム
このセクションでは、2つの行列を乗算する方法を説明します。行列の乗算は、この条件を満たす場合にのみ実行できます。 2つの行列がAとBであり、それらの次元がA(m x n)とB(p x q)であるとすると、結果の行列は、n=pの場合にのみ見つけることができます。その場合、結果の行列Cの次数は(m x q)になります。
アルゴリズム
matrixMultiply(A, B): Assume dimension of A is (m x n), dimension of B is (p x q) Begin if n is not same as p, then exit otherwise define C matrix as (m x q) for i in range 0 to m - 1, do for j in range 0 to q – 1, do for k in range 0 to p, do C[i, j] = C[i, j] + (A[i, k] * A[k, j]) done done done End
例
#include<iostream>
using namespace std;
int main() {
int product[10][10], r1=3, c1=3, r2=3, c2=3, i, j, k;
int a[3][3] = {
{2, 4, 1},
{2, 3, 9},
{3, 1, 8}
};
int b[3][3] = {
{1, 2, 3},
{3, 6, 1},
{2, 4, 7}
};
if (c1 != r2) {
cout<<"Column of first matrix should be equal to row of second matrix";
} else {
cout<<"The first matrix is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c1; ++j)
cout<<a[i][j]<<" ";
cout<<endl;
}
cout<<endl;
cout<<"The second matrix is:"<<endl;
for(i=0; i<r2; ++i) {
for(j=0; j<c2; ++j)
cout<<b[i][j]<<" ";
cout<<endl;
}
cout<<endl;
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j) {
product[i][j] = 0;
}
for(i=0; i<r1; ++i)
for(j=0; j<c2; ++j)
for(k=0; k<c1; ++k) {
product[i][j]+=a[i][k]*b[k][j];
}
cout<<"Product of the two matrices is:"<<endl;
for(i=0; i<r1; ++i) {
for(j=0; j<c2; ++j)
cout<<product[i][j]<<" ";
cout<<endl;
}
}
return 0;
} 出力
The first matrix is: 2 4 1 2 3 9 3 1 8 The second matrix is: 1 2 3 3 6 1 2 4 7 Product of the two matrices is: 16 32 17 29 58 72 22 44 66
-
フロイドウォーシャルアルゴリズム
Floyd-Warshallアルゴリズムを使用して、特定の重み付きグラフからすべてのペアの最短経路問題を見つけます。このアルゴリズムの結果として、グラフ内の任意のノードから他のすべてのノードまでの最小距離を表す行列が生成されます。 最初、出力行列はグラフの指定されたコスト行列と同じです。その後、出力行列はすべての頂点kを中間頂点として更新されます。 このアルゴリズムの時間計算量はO(V ^ 3)です。ここで、Vはグラフ内の頂点の数です。 入力と出力 Input: The cost matrix of the graph. 0 3 6 ∞ ∞ ∞ &
-
C++でシュトラッセンの行列方程式を覚える簡単な方法
これは、分割統治法に基づく行列乗算アルゴリズムです。 方法。同じサイズの2つの行列を乗算するために使用されます 2つの行列の乗算を見つける- シュトラッセンのアルゴリズム 乗算を単純化することにより、乗算のオーバーヘッドを削減します。 シュトラッセンのアルゴリズムを使用して行われた乗算は次のとおりです。 M1 =a *(f --h) M2 =(a + b)* h M3 =(c + d)* e M4 =d *(g-e) M5 =(a + d)*(e + h) M6 =(b --d)*(g + h) M7 =(a --c)*(e + f) こ