在将有效的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
输出按预期完美读取。 / p>
我错过了什么?
答案 0 :(得分:0)
由于您未在matlab程序中的fopen()或fwrite()中指定“machine format”,因此默认情况下它将使用“本机”系统字节顺序。
您需要在Matlab中使用“machineformat”字段创建文件时指定二进制格式。
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');