转置 C# 中的矩阵
矩阵转置将矩阵通过对角线翻转,将行元素放在列上,列元素放在行上。
例如 −
Matrix before Transpose: 123 456 789 Matrix after Transpose: 147 258 369
我们来看一个用 C# 编写矩阵转置的示例 −
示例
using System; public class Demo { public static void Main() { int i, j, m, n; int[, ] arr1 = new int[30, 30]; int[, ] arr2 = new int[30, 30]; Console.Write("
Enter the number of rows and columns of the matrix :
"); Console.Write("Rows entered = "); m = Convert.ToInt32(Console.ReadLine()); Console.Write("Columns entered = "); n = Convert.ToInt32(Console.ReadLine()); Console.Write("Set elements in the matrix...
"); for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { Console.Write("
[{0}],[{1}] : ", i, j); arr1[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.Write("
Matrix before Transpose:
"); for (i = 0; i < m; i++) { Console.Write("
"); for (j = 0; j < n; j++) Console.Write("{0}\t", arr1[i, j]); } for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { arr2[j, i] = arr1[i, j]; } } Console.Write("
Matrix after Transpose: "); for (i = 0; i < m; i++) { Console.Write("
"); for (j = 0; j < n; j++) { Console.Write("{0}\t", arr2[i, j]); } } Console.Write("
"); } }
运行以上程序将会产生以下结果。在其中,需要让用户输入行数、列数,以及矩阵元素 −
Enter the number of rows and columns of the matrix :3 3 Rows entered = 3 Columns entered 3 Set elements in the matrix... [0],[0] : 1 [0],[1] : 2 [0],[2] : 3 [1],[0] : 4 [1],[1] : 5 [1],[2] : 6 [2],[0] : 7 [2],[1] : 8 [2],[2] : 9 Matrix before Transpose: 123 456 789 Matrix after Transpose: 147 258 369
广告