二分查找
快速实用的指南,用Java计算矩阵转置。 给定矩阵的转置只是改变值和顺序而已。
1.概述
在本文中,您将学习如何使用简单的for循环查找给定矩阵的转置。
您可以阅读前面有关使用数组对两个矩阵进行加法和乘法的文章。
转置不过是将行与列交换,顺序也将被交换。 最后,它产生新的矩阵。
Matrix M : [A11, A12
A21, A22
A31, A32]
Transpose of Matrix M: [ A11, A21, A31
A12, A22, A32]
转置矩阵的阶数:
矩阵M顺序:3 X 2
2.查找矩阵转置的示例程序
只需要一个矩阵即可找到转置。 只需两个for循环即可完成此操作。
在下面的程序中,添加了两个方法doMatricTranspose()来生成矩阵的转置,而其他doPrintResultMatric()则用于打印给定的矩阵。
将值从行移动到列。 输入矩阵的顺序为2 X 3,具有2行3列。
调用doMatricTranspose()并生成输出矩阵后,顺序为3 X 2(3行2列)。 并且输入矩阵的所有值也将与其位置交换,例如A12至A21,A31至A13等。
核心逻辑:
主逻辑被添加到单独的函数中以供重用。
result[j][i] = matrix[i][j];
package com.javaprogramto.programs.arrays.matrix;
public class MatrixTranspose {
public static void main(String[] args) {
// creating the first matrix using arrays
int [][] matrix = { { 1 , 2 , 3 }, { 4 , 5 , 6 } };
//Printing the original matrix
System.out.println( "Input Matrix : " );
doPrintResultMatric(matrix);
// Matrix 1 rows and columns length
int rows = matrix.length;
int columns = matrix[ 0 ].length;
// Calling a function for matrix transpose core logic
int [][] result = doMatricTranspose(matrix, rows, columns);
// printing the result
System.out.println( "Transpose of Matrix : " );
doPrintResultMatric(result);
}
/**
* Calculates the matrix transpose for given inputs arrays.
*
* @param matrix1
* @param rows1
* @param columns1
* @return
*/
private static int [][] doMatricTranspose( int [][] matrix, int rows, int columns) {
// output array for storing the transpose result. order needs to be swapped.
int [][] result = new int [columns][rows];
for ( int i = 0 ; i < rows; i++) {
for ( int j = 0 ; j < columns; j++) {
result[j][i] = matrix[i][j];
}
}
return result;
}
// prints the given matrix
private static void doPrintResultMatric( int [][] result) {
for ( int i = 0 ; i < result.length; i++) {
for ( int j = 0 ; j < result[ 1 ].length; j++) {
System.out.print(result[i][j] + " " );
}
System.out.println();
}
}
}
输出:
Input Matrix :
1 2 3
4 5 6
Transpose of Matrix :
1 4
2 5
3 6
3.结论
在本文中,您已经了解了如何获取给定矩阵的转置。 上面的示例适用于任何顺序的所有类型输入。
与往常一样,所示示例在GitHub上进行。
翻译自: https://www.javacodegeeks.com/2020/11/java-program-to-find-transpose-of-a-matrix.html
二分查找