I am trying to use the functionality of the reshape function available in MATLAB in Java. Are there any implementations of reshape available in Java?
I found this (modified a little) on the sun forums.
public class Test {
public static void main(String[] args) {
double[][] ori = new double[][] { {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12} };
double[][] res = reshape(ori,2,6);
for(int i = 0;i<ori.length;i++){
for(int j = 0;j<ori[0].length;j++){
System.out.print(ori[i][j]+" ");
}
System.out.println("");
}
System.out.println("");
for(int i = 0;i<res.length;i++){
for(int j = 0;j<res[0].length;j++){
System.out.print(res[i][j]+" ");
}
System.out.println("");
}
}
public static double[][] reshape(double[][] A, int m, int n) {
int origM = A.length;
int origN = A[0].length;
if(origM*origN != m*n){
throw new IllegalArgumentException("New matrix must be of same area as matix A");
}
double[][] B = new double[m][n];
double[] A1D = new double[A.length * A[0].length];
int index = 0;
for(int i = 0;i<A.length;i++){
for(int j = 0;j<A[0].length;j++){
A1D[index++] = A[i][j];
}
}
index = 0;
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
B[j][i] = A1D[index++];
}
}
return B;
}
}
test output is
1.0 2.0 3.0
4.0 5.0 6.0
7.0 8.0 9.0
10.0 11.0 12.0
1.0 3.0 5.0 7.0 9.0 11.0
2.0 4.0 6.0 8.0 10.0 12.0
A bit late, but for any future visitors. There is the Eclipse January, which supports such operation
This is a library for handling Data in Java. It is inspired in part by NumPy and aims to provide similar functionality.
It does have support for reshape
function on Dataset
.
You can go over the BasicExample
(code from the above example)
Dataset another = DatasetFactory
.createFromObject(new double[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 })
.reshape(3, 3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With