You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java矩阵转置异常:调用转置方法后结果与原矩阵一致

矩阵转置后结果与原矩阵相同的问题解决

我要实现矩阵转置功能,创建了矩阵并编写了transposeMatrix方法,但调用该方法后得到的结果和原矩阵完全相同。

我的代码

import java.util.Scanner;
import java.util.Random;
public class Matrix {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter the height of array: ");
        int height = input.nextInt();

        System.out.println("Enter the width of array: ");
        int width = input.nextInt();

        int[][] array =  new int[height][width];
        int[][] transposed_matrix =  new int[width][height];
        Random rand_num = new Random();
        for(int i = 0; i < height; i++)
        {
            for(int j = 0; j < width; j++)
            {
                array[i][j]=rand_num.nextInt(1, 50);
                System.out.print(array[i][j] + "\t");
            }
            System.out.print("\n");
        }
        System.out.println("Transposed matrix: \n");
        transposeMatrix(array, transposed_matrix, height, width);
    }

    public static void transposeMatrix(int[][] array, int[][] transposed_matrix, int height, int width){
        for(int i = 0; i < height; i++)
        {
            for(int j = 0; j < width; j++)
            {
                transposed_matrix[j][i] = array[i][j];
                System.out.print(transposed_matrix[j][i] + "\t");
            }
            System.out.print("\n");
        }

    }
}

预期输出

34  34  24  26
41  44  43  40
22  40  47  3
Transposed matrix:
34  41  22
34  44  40
24  43  47
26  40  3

实际输出

34  34  24  26
41  44  43  40
22  40  47  3
Transposed matrix:
34  34  24  26
41  44  43  40
22  40  47  3

问题原因与解决方法

问题出在transposeMatrix方法的打印逻辑上:

  • 转置赋值的逻辑是正确的(transposed_matrix[j][i] = array[i][j]),但打印时仍按照原矩阵的行列顺序输出(外层循环遍历原矩阵的行,内层遍历原矩阵的列,每行打印width个元素),导致输出内容和原矩阵一致。

修改方法:先完成转置矩阵的赋值,再按照转置矩阵的行列结构打印。修改后的transposeMatrix方法如下:

public static void transposeMatrix(int[][] array, int[][] transposed_matrix, int height, int width){
    // 先完成转置赋值
    for(int i = 0; i < height; i++){
        for(int j = 0; j < width; j++){
            transposed_matrix[j][i] = array[i][j];
        }
    }
    // 按转置矩阵的行列打印
    for(int i = 0; i < width; i++){
        for(int j = 0; j < height; j++){
            System.out.print(transposed_matrix[i][j] + "\t");
        }
        System.out.print("\n");
    }
}

这样修改后,转置矩阵会按照正确的行列结构输出,得到预期的结果。

内容的提问来源于stack exchange,提问作者Yul4onok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 03:22:43