I'm trying to transpose a one dimensional array from a text file. I feel like I'm almost there, but I'm doing something stupid.
Here is the code below, with comments.
import java.io.*;
public class Matrix {
int row;
int col;
int value;
Matrix[] M;
int n;
int mcol;
int mrow;
Matrix[] Mt;
Matrix() {}
Matrix(String filename) {
try {
FileReader file=new FileReader(filename);
BufferedReader buff=new BufferedReader(file);
String line = buff.readLine();
String[] tokens = line.split(" ");
int mrow = Integer.parseInt(tokens[0]);
int mcol = Integer.parseInt(tokens[1]);
int n = Integer.parseInt(tokens[2]);
M = new Matrix[n];
Mt = new Matrix[n]; //This and the for loop is to test to see if I actually could assign values to Mt, which I could.
for (int m=0;m<n;m++){
Mt[m] = new Matrix();
Mt[m].row = m;
Mt[m].col = m;
Mt[m].value = m;
}
for (int i=0; i<n; i++) {
line = buff.readLine();
tokens = line.split(" ");
M[i] = new Matrix();
M[i].row = Integer.parseInt(tokens[0]);
M[i].col = Integer.parseInt(tokens[1]);
M[i].value = Integer.parseInt(tokens[2]);
}
buff.close();
file.close();
} catch (Exception e) {
System.out.println(e);
}
}
public void display() {
System.out.println("Row\tCol\tValue\n");
for (int i=0; i<M.length; i++) {
System.out.printf("%d\t%d\t%d\n", M[i].row, M[i].col, M[i].value);
}
}
public void naivetranspose(){
for (int i=0; i < mcol; i++) {
for (int j=0; j <= n ; j++) {
if (M[j].col == i){
Mt[j] = new Matrix(); //Here, I'm attempting to associate each index of Mt with a .row, .col and .value value, which is the transpose of the main M Matrix. Not working though.
Mt[j].row = M[j].col;
Mt[j].col = M[j].row;
Mt[j].value = M[j].value;
}
}}
Mt[1].value = 9000; // This is another test to see if I can attach value to one array, if not by the way I want to.
System.out.println("Row\tCol\tValue\n");
for (int i=0; i<Mt.length; i++) {
System.out.printf("%d\t%d\t%d\n", Mt[i].row, Mt[i].col, Mt[i].value);
}
}
public static void main(String[] args) {
Matrix matrix = new Matrix("m5x5.mat");
matrix.display();
matrix.naivetranspose();
}
}I've made several tests to see if I could fill in Mt[]'s values elsewhere, which I could. I'm just having problem with that transpose method.
The code I've posted gives the following result:
5 5 11
0 3 297
1 0 230
1 4 291
2 0 390
2 2 250
2 3 286
2 4 330
3 2 333
3 4 464
4 0 184
4 3 347
0 0 0
1 1 9000
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
10 10 10
I need that second matrix to be the transpose of the first one. Please help if you can.