【问题标题】:Is the MATLAB function of 'reshape' available in any Java library?'reshape' 的 MATLAB 函数是否在任何 Java 库中可用?
【发布时间】:2011-02-22 01:38:09
【问题描述】:

我正在尝试在 Java 中使用 MATLAB 中可用的 reshape 函数的功能。 Java 中是否有任何 reshape 的实现?

【问题讨论】:

    标签: java matlab reshape


    【解决方案1】:

    我在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;
        }
    }
    

    测试输出是

    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 
    

    【讨论】:

    • 非常感谢 Glowcoder !你能建议我一些将一个维度重塑到另一个维度的想法吗?我希望将 1 维(a[50400])数组转换为 7 维数组(b[2][12][4][5][5][7][3])。另一种情况是将2d数组(c[1260][12])转换成3d数组(d[60][21][12])
    【解决方案2】:

    有点晚了,但对于任何未来的访客。 有Eclipse January,支持这样的操作

    这是一个用于处理 Java 数据的库。它部分受到 NumPy 的启发,旨在提供类似的功能。

    它确实支持Dataset 上的reshape 功能。 你可以去BasicExample

    (上例中的代码)

    Dataset another = DatasetFactory
                        .createFromObject(new double[] { 1, 1, 2, 3, 5, 8, 13, 21, 34 })
                        .reshape(3, 3);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 2015-10-17
      相关资源
      最近更新 更多