Java利用jmatio读取.mat文件中的多维矩阵

Jmatio包只提供了二维数组的读取,对于多维数组,需要自己编写代码手动进行组装。需要注意的是,Jmatio在读取.mat文件中的数据时,是按照低维读向高维数据的顺序来构建字节流,而不是我们平常的先读取最高维度的数据,再依次读取低维数据。

注意,如果先从低维开始读,那么构建出来的数组数据会与.mat文件中的矩阵数据不一致

下面看代码:

    public float[][][][] readMat(String filePath) throws IOException {

        MatFileReader read = new MatFileReader(filePath);
        MLArray mlArray = read.getMLArray(filevaraible);
        shape = mlArray.getDimensions();
        int sizex = shape[0];
        int sizey = shape[1];
        int sizez = shape[2];
        int time = shape[3];
        MLSingle d =(MLSingle)mlArray;
        // get data byte buffer
        ByteBuffer buffer = d.getRealByteBuffer();
        // save matrix element
        float[][][][] mat = new float[sizex][sizey][sizez][time];

        /**
         *  transfer buffer to 4-d array
         * */
        for(int t = 0 ; t <  time; ++t) {
            for (int z = 0; z < sizez; ++z) {
                for (int y = 0; y < sizey; ++y) {
                    for (int x = 0; x < sizex; ++x) {
                        mat[x][y][z][t] = buffer.getFloat();
                    }
                }
            }
        }
        return mat;
    }

若有疑问请在评论区留言~

原文地址:https://www.cnblogs.com/gagag/p/14651052.html