首先我们需要理解转置的含义:
就是行变成列,列变成行。
例如:
3*3矩阵的转置:
100 200 300
400 500 600
700 800 900
转置后为:
100 400 700
200 500 800
300 600 900
Java代码实现:
public class NewClass6 {
public static void main(String[] args) {
// TODO code application logic here
int a [][] =new int[5][3];
System.out.println("请输入5*3矩阵的值:");
for(int i=0;i<5;i++)
{
for(int j=0;j<3;j++)
{
Scanner scanner = new Scanner(System.in);//建立Scanner对象,通过System.in来读取键盘输入数据
a[i][j] = scanner.nextInt();
}
}
System.out.println("数组长度:"+a.length);
int x,y;
System.out.println("5*3矩阵的值:");
for(x=0;x<5;x++)
{
for(y=0;y<3;y++)
{
System.out.print(" "+a[x][y]);
}
System.out.println("\n");
}
int i,j,temp=0;
int b[][];
b=new int[3][5];
for(i = 0; i < 3;i++)
{
for(j = 0; j < 5; j++)
{
b[i][j]=a[j][i];
}
}
System.out.println("3*5矩阵的值:");
for(x=0;x<3;x++)
{
for(y=0;y<5;y++)
{
System.out.print(" "+b[x][y]);
}
System.out.println("\n");
}
}
}
运行结果:
请输入53矩阵的值:
23
34
54
56
78
76
65
67
87
75
454
54
43
32
34
数组长度:5
53矩阵的值:
23 34 54
56 78 76
65 67 87
75 454 54
43 32 34
3*5矩阵的值:
23 56 65 75 43
34 78 67 454 32
54 76 87 54 34