in place transpose in a matrix in java

www.lau‮oc.irutt‬m
in place transpose in a matrix in java

To transpose a matrix in place in Java, you can use a nested loop to iterate over the matrix and swap the elements in a way that the rows become columns and the columns become rows.

Here is an example of how to transpose a matrix in place in Java:

public class Main {
    public static void main(String[] args) {
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int n = matrix.length;

        // Transpose the matrix in place
        for (int i = 0; i < n; i++) {
            for (int j = i; j < n; j++) {
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }

        // Print the transposed matrix
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

This code will transpose the matrix {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} in place and print the result to the console:

1 4 7
2 5 8
3 6 9

Note that this code assumes that the matrix is a square matrix with the same number of rows and columns. If the matrix is not a square matrix, you can modify the code to only transpose the elements that are within the bounds of the matrix.

Created Time:2017-11-01 22:29:51  Author:lautturi