2DArrayを使用した行列の転置プログラムをJavaで書いてみます。
目次
行列クラス
public class Matrix {
int[][] array;
int[][] arrayT;
int i;
int j;
boolean isT;
...
}コンストラクタ
配列は行列どちらも数が指定されているため、あらかじめ転置後の行列も初期化しておきます。
public Matrix(int i, int j){
this.isT = false;
this.i = i;
this.j = j;
this.array = new int[i][j];
this.arrayT = new int[j][i];
}行列可視化メソッド
転置状態を追跡する変数に応じて出力を変えます。
public String toString(){
String result = "";
String tmp;
if (!isT){
for (int i = 0;i <this.i;i++){
tmp = "|";
for (int j = 0;j <this.j;j++){
tmp += this.array[i][j];
if (j == this.j-1){
tmp += "|\n";
}
}
result += tmp;
}
return result;
}else{
for (int i = 0;i <this.j;i++){
tmp = "|";
for (int j = 0;j <this.i;j++){
tmp += this.array[j][i];
if (j == this.i-1){
tmp += "|\n";
}
}
result += tmp;
}
return result;
}
}転置メソッド
public void transpose(){
if (isT){
isT = false;
}else{
isT = true;
}
for (int i = 0;i <this.j;i++){
for (int j = 0;j <this.i;j++){
this.arrayT[i][j] = this.array[j][i];
}
}
}mainメソッド
うまく転置できているか確かめてみます。
public static void main(String[] args) {
Matrix mat = new Matrix(5, 10);
for (int i = 0;i <mat.i;i++){
int num = 0;
for (int j = 0;j <mat.j;j++){
mat.array[i][j] = num;
num ++;
}
}
System.out.println(mat);
mat.transpose();
System.out.println(mat);
mat.transpose();
System.out.println(mat);
}実行結果
|0123456789|
|0123456789|
|0123456789|
|0123456789|
|0123456789|
|00000|
|11111|
|22222|
|33333|
|44444|
|55555|
|66666|
|77777|
|88888|
|99999|

