C++程式查詢矩陣的範數和跡


二維陣列或矩陣在許多應用中非常有用。矩陣具有行和列,並在其中儲存數字。在C++中,我們也可以使用多維陣列定義二維矩陣。在本文中,我們將瞭解如何使用C++計算給定矩陣的範數和跡。

範數是矩陣中所有元素之和的平方根。跡是主對角線上元素之和。讓我們看看演算法和C++程式碼表示。

矩陣範數

$\begin{bmatrix} 5 & 1& 8\newline 4 & 3& 9\newline 2& 7& 3\ \end{bmatrix},$

Sum of all elements: (5 + 1 + 8 + 4 + 3 + 9 + 2 + 7 + 3) = 42
Normal: (Square root of the sum of all elements) = √42 = 6.48

在上面的示例中,我們取了一個3 x 3矩陣,在這裡我們得到所有元素的總和,然後對其進行平方根運算。讓我們看看演算法,以便更好地理解。

演算法

  • 讀取矩陣M作為輸入
  • 假設M有n行和n列
  • sum := 0
  • 對於i從1到n,執行
    • 對於j從1到n,執行
      • sum := sum + M[ i ][ j ]
    • 結束迴圈
  • 結束迴圈
  • res := sum的平方根
  • 返回res

示例

#include <iostream>
#include <cmath>
#define N 5
using namespace std;
float solve( int M[ N ][ N ] ){
   int sum = 0;
   for ( int i = 0; i < N; i++ ) {
      for ( int j = 0; j < N; j++ ) {
         sum = sum + M[ i ][ j ];
      }
   }
   return sqrt( sum );
}
int main(){
   int mat1[ N ][ N ] = {
      {5, 8, 74, 21, 69},
      {48, 2, 98, 6, 63},
      {85, 12, 10, 6, 9},
      {6, 12, 18, 32, 5},
      {8, 45, 74, 69, 1},
   };
   cout << "Normal of the first matrix is: " << solve( mat1 ) << endl;
   int mat2[ N ][ N ] = {
      {6, 8, 35, 21, 87},
      {99, 2, 36, 326, 25},
      {15, 215, 3, 157, 8},
      {96, 115, 17, 5, 3},
      {56, 4, 78, 5, 10},
   };
   cout << "Normal of the second matrix is: " << solve( mat2 ) << endl;
}

輸出

Normal of the first matrix is: 28.0357
Normal of the second matrix is: 37.8418

矩陣跡

$\begin{bmatrix} 5 & 1& 8\newline 4 & 3& 9\newline 2& 7& 3\ \end{bmatrix},$

Sum of all elements in main diagonal: (5 + 3 + 3) = 11 which is
the trace of given matrix

在上面的示例中,我們取了一個3 x 3矩陣,在這裡我們得到主對角線上所有元素的總和。該總和是矩陣的跡。讓我們看看演算法,以便更好地理解。

演算法

  • 讀取矩陣M作為輸入
  • 假設M有n行和n列
  • sum := 0
  • 對於i從1到n,執行
    • sum := sum + M[ i ][ i ]
  • 結束迴圈
  • 返回sum

示例

#include <iostream>
#include <cmath>
#define N 5
using namespace std;
float solve( int M[ N ][ N ] ){
   int sum = 0;
   for ( int i = 0; i < N; i++ ) {
      sum = sum + M[ i ][ i ];
   }
   return sum;
}
int main(){
   int mat1[ N ][ N ] = {
      {5, 8, 74, 21, 69},
      {48, 2, 98, 6, 63},
      {85, 12, 10, 6, 9},
      {6, 12, 18, 32, 5},
      {8, 45, 74, 69, 1},
   };
   cout << "Trace of the first matrix is: " << solve( mat1 ) << endl;
   int mat2[ N ][ N ] = {
      {6, 8, 35, 21, 87},
      {99, 2, 36, 326, 25},
      {15, 215, 3, 157, 8},
      {96, 115, 17, 5, 3},
      {56, 4, 78, 5, 10},
   };
   cout << "Trace of the second matrix is: " << solve( mat2 ) << endl;
}

輸出

Trace of the first matrix is: 50
Trace of the second matrix is: 26

結論

範數和跡是矩陣運算。要執行這兩個運算,我們需要一個方陣(對於跡需要方陣)。範數只是矩陣中所有元素之和的平方根,跡是矩陣主對角線上元素之和。矩陣可以使用C++中的二維陣列表示。這裡我們取了兩個5行5列的矩陣示例(總共25個元素)。訪問矩陣需要使用索引操作的迴圈語句。對於範數計算,我們需要遍歷每個元素,因此需要兩個巢狀迴圈。此程式的複雜度為O(n2)。對於跡,因為我們只需要檢視主對角線,所以行和列索引將相同。因此,只需要一個for迴圈。它可以在O(n)時間內計算出來。

更新於: 2022年12月14日

330 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.