在 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP