给定大小为nxn的矩阵,任务可以将任何类型的给定矩阵转换为对角矩阵。
对角矩阵是nxn矩阵,其所有非对角元素均为零,对角元素可以为任何值。
下面给出的是将非对角元素转换为0的示意图。
$$\ begin {bmatrix} 1&2&3 \\ 4&5&6 \\ 7&8&9 \ end {bmatrix} \:\\ rightarrow \:\ begin {bmatrix} 1&0&3 \\ 0 &5&0 \\ 7&0&9 \ end {bmatrix} $$
该方法是为所有非对角元素开始一个循环,为对角元素开始另一个循环,并用零替换非对角元素的值,并使对角元素保持不变。
Input-: matrix[3][3] = {{ 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 }} Output-: {{ 1, 0, 3}, { 0, 5, 0}, { 7, 0, 9}} Input-: matrix[3][3] = {{ 91, 32, 23 }, { 40, 51, 26 }, { 72, 81, 93 }} Output-: {{ 91, 0, 23}, { 0, 51, 0}, { 72, 0, 93}}
Start Step 1-> define macro for matrix size as const int n = 10 Step 2-> Declare function for converting to diagonal matrix void diagonal(int arr[][n], int a, int m) Loop For int i = 0 i < a i++ Loop For int j = 0 j < m j++ IF i != j & i + j + 1 != a Set arr[i][j] = 0 End End End Loop For int i = 0 i < a i++ Loop For int j = 0 j < m j++ Print arr[i][j] End Print \n End Step 2-> In main() Declare matrix as int arr[][n] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } Call function as diagonal(arr, 3, 3) Stop
#include <iostream> using namespace std; const int n = 10; //在nxn矩阵的对角线上打印0- void diagonal(int arr[][n], int a, int m) { for (int i = 0; i < a; i++) { for (int j = 0; j < m; j++) { if (i != j && i + j + 1 != a) arr[i][j] = 0; } } for (int i = 0; i < a; i++) { for (int j = 0; j < m; j++) { cout << arr[i][j] << " "; } cout << endl; } } int main() { int arr[][n] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; diagonal(arr, 3, 3); return 0; }
输出结果
如果我们运行以上代码,它将在输出后产生
0 2 0 4 0 6 0 8 0