有人可以解释这个Java代码来转置矩阵吗?

时间:2015-02-04 18:19:35

标签: java for-loop multidimensional-array transpose

我面前有一个java代码,但我不明白 toString方法转置方法会发生什么。

我的意思是for循环中发生了什么?

如果有人能帮助我,我将感激不尽。

这是另一种方法

public static int[][] transpose(int[][]m){



    int[][] temp = new int[m[0].length][m.length];
    for (int i = 0; i < m.length; i++){
        for (int j = 0; j < m[0].length; j++){
            temp[j][i] = m[i][j];
        }

    }
        return temp;
}

这是代码

package question5;

import java.util.Arrays;
import java.util.Scanner;

public class Matrix {

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        int[][] multarray = new int[4][4];

        System.out.print("Enter your Numbers between 1 and 16");
        for(int i = 0 ; i < multarray.length; i++){
            for(int j = 0 ;j < multarray.length; j++){

                multarray[i][j] = sc.nextInt();
            }
        }

        for(int row = 0 ; row<multarray.length; row++){
            for(int col = 0; col< multarray.length; col++){
                System.out.print(multarray[row][col] + " ");
            }
            System.out.println();




        }
        System.out.println();
        System.out.println();
        System.out.println("Transpose Array is : ");


        System.out.println(toString(transpose(multarray)));
    }

    public static int[][] transpose(int[][]m){

        int rows = m.length;
        int cols = m[0].length;

        int t[][] = new int [cols][];
        for(int trow = 0 ; trow < cols; trow++){
            t[trow] = new int[rows];
        }

        for(int row = 0; row< rows;row++){
            for(int col = 0; col<cols; col++){
                int tcol = rows-row-1;
                int trow = cols-col-1;
                t[trow][tcol] = m[row][col];
            }
        }
        return t;
    }

    public static String toString(int[][] m) {
        StringBuilder text = new StringBuilder();
        for (int row = 0; row < m.length; row++) {
            int r[] = m[row];
            for (int col = 0; col < r.length; col++) {
                if (col > 0) text.append(", ");
                text.append(r[col]);
            }
            text.append("\n");
        }
        return text.toString();
    }
}

1 个答案:

答案 0 :(得分:3)

这两行是transpose方法的“核心”:

int tcol = rows-row-1;
int trow = cols-col-1;

给定一对(row, column)表示方形矩阵中单元格的坐标,它们在转置矩阵中计算其目标坐标,这只是矩阵主对角线的反射。

以下是对此的说明:

Illustration of how transposition works.

(0, 0)