ในบทความนี้ เราจะเข้าใจวิธีการหาทรานสโพสของเมทริกซ์ เมทริกซ์มีการจัดเรียงแถวและคอลัมน์ขององค์ประกอบ เมทริกซ์ที่มี m แถวและ n คอลัมน์สามารถเรียกได้ว่าเป็นเมทริกซ์ขนาด m × n พบทรานสโพสของเมทริกซ์โดยการเปลี่ยนแถวของมันเป็นคอลัมน์หรือคอลัมน์เป็นแถว
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
The matrix is defined as: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4
ผลลัพธ์ที่ต้องการจะเป็น −
The transpose of the matrix is: 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
อัลกอริทึม
Step 1 - START Step 2 - Declare two integer matrices namely input_matrix and result_matrix. Step 3 - Define the values. Step 4 - Iterate over each element of the matrix using two for-loops, assign the element at [i][j] position of the matrix to the [j][i] position of the result_matrix. Step 5 - Display the result_matrix. Step 6 - Stop
ตัวอย่างที่ 1
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
public class MatrixTranspose {
static final int matrix_size = 4;
public static void main (String[] args) {
int input_matrix[][] = {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}
};
System.out.println("The matrix is defined as: \n");
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
int result_matrix[][] = new int[matrix_size][matrix_size];
for (int i = 0; i < matrix_size; i++)
for (int j = 0; j < matrix_size; j++)
result_matrix[i][j] = input_matrix[j][i];
System.out.println("\nThe transpose of the matrix is: ");
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
System.out.print(result_matrix[i][j] + " ");
}
System.out.println();
}
}
} ผลลัพธ์
The matrix is defined as: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 The transpose of the matrix is: 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
ตัวอย่างที่ 2
ในที่นี้ เราสรุปการดำเนินการเป็นฟังก์ชันที่แสดงการเขียนโปรแกรมเชิงวัตถุ
public class MatrixTranspose {
static final int matrix_size = 4;
static void transpose(int input_matrix[][]) {
int result_matrix[][] = new int[matrix_size][matrix_size];
for (int i = 0; i < matrix_size; i++)
for (int j = 0; j < matrix_size; j++)
result_matrix[i][j] = input_matrix[j][i];
System.out.println("\nThe transpose of the matrix is: ");
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
System.out.print(result_matrix[i][j] + " ");
}
System.out.println();
}
}
public static void main (String[] args) {
int input_matrix[][] = {
{1, 1, 1, 1},
{2, 2, 2, 2},
{3, 3, 3, 3},
{4, 4, 4, 4}
};
System.out.println("The matrix is defined as: \n");
for (int i = 0; i < matrix_size; i++) {
for (int j = 0; j < matrix_size; j++) {
System.out.print(input_matrix[i][j] + " ");
}
System.out.println();
}
transpose(input_matrix);
}
} ผลลัพธ์
The matrix is defined as: 1 1 1 1 2 2 2 2 3 3 3 3 4 4 4 4 The transpose of the matrix is: 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4