0

MATLAB在将工作片段翻译成相应的片段时,我遇到了很多问题JAVA

MATLAB的工作原理如下:

fid = fopen('test.wnd','w');
fwrite(fid, -99, 'int16');
fwrite(fid, 7, 'int16');
fwrite(fid, 92, 'int32');
fwrite(fid, 3, 'int32');
fwrite(fid, 75.0, 'float32');
fwrite(fid, 75.0, 'float32');
fwrite(fid, 3.0, 'float32');
fwrite(fid, 2048, 'int32');
fwrite(fid, 8.0, 'float32');
fwrite(fid, 0, 'float32');
fwrite(fid, 0, 'float32');
fwrite(fid, 340.2, 'float32');
fwrite(fid, 0, 'int32');
fwrite(fid, 12, 'int32');
fwrite(fid, 3, 'int32');
fwrite(fid, 3, 'int32');
fwrite(fid, 0, 'float32');
fwrite(fid, 0, 'float32');
fwrite(fid, 113.4, 'float32');
fwrite(fid, 0, 'float32');
fwrite(fid, 0, 'float32');
fwrite(fid, 27.72, 'float32');
fwrite(fid, 12, 'float32');
fwrite(fid, 340.2, 'float32');

Scale = [1.0 .8 .5];
Offset = [8.0 0 0];

v = zeros(3*3,1);

for it = 1:nt
    cnt = 1;
    for iz = 1:nz
        for iy = y_ix
            for k=1:nffc
                v(cnt) =  ((velocity(it,k,iy,iz) - Offset(k))/Scale(k)*1000);
                cnt = cnt + 1;                
            end %for k
        end %iy
    end % iz 

    fwrite( fid_wnd, v, 'int16' );

end %it
fclose(fid);

因此,在 中JAVA,我尝试了这个:

DataOutputStream dos = new DataOutputStream(new FileOutputStream("C:/Users/fperrone/Desktop/test.wnd"));
dos.writeShort(-99);
dos.writeShort(7);
dos.writeInt(92);
dos.writeInt(3);        
dos.writeFloat((float)75.0);
dos.writeFloat((float)75.0);
dos.writeFloat((float)2.4);
dos.writeInt(2048);
dos.writeFloat((float)8.0);
dos.writeFloat((float)0);
dos.writeFloat((float)0);
dos.writeFloat((float)340.2);
dos.writeInt(0);
dos.writeInt(67);
dos.writeInt(3);
dos.writeInt(3);
dos.writeFloat((float)0);
dos.writeFloat((float)0);
dos.writeFloat((float)113.4);
dos.writeFloat((float)0);
dos.writeFloat((float)0);
dos.writeFloat((float)27.72);
dos.writeFloat((float)12);
dos.writeFloat((float)340.2);
double[] Offset = {8.0, 0.0, 0.0};
double[] Scale = {1.0, .8, .5};
short v[] = new short[9];
        for(int it = 0; it < 4096; ++it){
            for(int comp = 0; comp < 3; ++comp){
                int count = 0;
                for(int iy = 0; iy < 3; ++iy){
                    for(int iz = 0; iz < 3; ++iz){
                        v[count] = (short) ((test[it][comp][iy][iz] - Offset[comp])/Scale[comp]*1000);
                        dos.writeShort(v[count]);
                        count += 1;
                    }
                }
            }           
        }       
        dos.close();

关键是,当我将JAVA输出与二进制文件用于的软件链接时,该软件不会读取任何信息,而MATLAB输出会按预期完美读取。

我错过了什么?

4

1 回答 1

0

由于您没有在 matlab 程序的 fopen() 或 fwrite() 中指定“机器格式”,因此默认情况下它将使用“本机”系统字节顺序。

您需要在使用“机器格式”字段在 Matlab 中创建文件时指定二进制格式。

fileID = fopen(filename,permission,machinefmt,encodingIn) fwrite(fileID, A, precision, skip, machineformat)

更多信息在这里: http: //www.mathworks.com/help/matlab/ref/fopen.html http://www.mathworks.com/help/matlab/ref/fwrite.html

要从 java 程序中正确读取,您需要这样做:fid = fopen('test.wnd','w','s');

于 2013-11-19T04:22:14.420 回答