在前面的示例中,使用了一个 3 x 3 矩阵,结果是 主要对角线中的元素数。矩阵的轨迹可以在总和中找到。让我们 看看算法来帮助我们理解。
算法
读取矩阵 M 作为输入
假设 M 有 n 行和 n 列
总和 := 0
对于范围从 1 到 n的 i,请执行
总和 := 总和 + M[ i ][ i ]
结束
返回总和
Example
#include#include#define N 7usingnamespace std ;floatsolve(int M [ N ][ N ]){int sum =0; // read elements through major diagonal, where row index and column index are same, both are i for(int i =0; i < N ; i ++){ sum = sum + M [ i ][ i ];}return sum ;}intmain(){int mat1 [ N ][ N ]={{5,8,74,21,69,78,25},{48,2,98,6,63,52,3},{85,12,10,6,9,47,21},{6,12,18,32,5,10,32},{8,45,74,69,1,14,56},{7,69,17,25,89,23,47},{98,23,15,20,63,21,56},}; cout <<"The Trace of the first matrix is: "<<solve( mat1 )<< endl ;int mat2 [ N ][ N ]={{6,8,35,21,87,8,26},{99,2,36,326,25,24,56},{15,215,3,157,8,41,23},{96,115,17,5,3,10,18},{56,4,78,5,10,22,58},{85,41,29,65,47,36,78},{12,23,87,45,69,96,12}}; cout <<"The Trace of the second matrix is: "<<solve( mat2 )<< endl ;}
输出
The Trace of the first matrix is: 129
The Trace of the second matrix is: 74
矩阵法线
所有元素的总和:(8 + 5 + 3 + 6 + 7 + 1 + 2 + 4 + 9) = 45
正态:(所有元素之和的平方根)= √45 = 6.708
在最后一个示例中,使用了 3 x 3 矩阵。我们首先计算了其所有条目的总和 在取其平方根之前。让我们看看帮助我们理解的算法。
算法
读取矩阵 M 作为输入
假设 M 有 n 行和 n 列
总和初始化为 0
对于范围从 1 到 n的 i,请执行
对于范围从 1 到 n 的 J,请执行
总和 := 总和 + M[ i ][ j ]
结束
结束
res := 和的平方根
返回分辨率
例
#include#include#define N 7usingnamespace std ;floatsolve(int M [ N ][ N ]){int sum =0; // go through each element. Using outer loop, access ith row, using inner loop access column. For cell (i, j) read the element and add it to the sum for(int i =0; i < N ; i ++){for(int j =0; j < N ; j ++){ sum = sum + M [ i ][ j ];}}returnsqrt( sum );}intmain(){int mat1 [ N ][ N ]={{5,8,74,21,69,78,25},{48,2,98,6,63,52,3},{85,12,10,6,9,47,21},{6,12,18,32,5,10,32},{8,45,74,69,1,14,56},{7,69,17,25,89,23,47},{98,23,15,20,63,21,56},}; cout <<"The Normal of the first matrix is: "<<solve( mat1 )<< endl ;int mat2 [ N ][ N ]={{6,8,35,21,87,8,26},{99,2,36,326,25,24,56},{15,215,3,157,8,41,23},{96,115,17,5,3,10,18},{56,4,78,5,10,22,58},{85,41,29,65,47,36,78},{12,23,87,45,69,96,12}}; cout <<"The Normal of the second matrix is: "<<solve( mat2 )<< endl ;}
输出
The Normal of the first matrix is: 41.1947
The Normal of the second matrix is: 49.4267