Im trying to convert a matlab script into python. The script read a binary file and reshape into a number of columns. The matlab script is:
fid=fopen(binary_file,'rb');
[inpar,ic]=fread(fid,4,'int');
if (ic<4) ; idata=[];return;end
nmagic=inpar(1);
nh=inpar(2);
nrpar=inpar(3);
nipar=inpar(4);
[rdata,ic]=fread(binary_file,[nh,nrpar],'float');
if (ic<nh*nrpar) ; return;end
[idata,ic]=fread(fid,[nh,nipar],'int');
if (ic<nh*nipar) ; return;end
The python code I tried is:
import numpy as np
inpar = np.fromfile(fid, dtype=np.int32)
nmagic, nh, nrpar, nipar = inpar
rdata = np.fromfile(fid, dtype=np.float32, count=nh * nrpar).reshape(nh, nrpar)
idata = np.fromfile(fid, dtype=np.int32, count=nh * nipar).reshape(nh, nipar)
I don't exactly know how Matlab is reshaping the data. Can anyone help me translate the code to achieve the same result in Python. A sample data is given here
Lets try to read the data with open in rb mod so it will be read in binary mode. Then we will use np.fromfile to read from the file.
import numpy as np
with open(binary_file, 'rb') as fid:
inpar = np.fromfile(fid, dtype=np.int32, count=4)
if inpar.size < 4:
idata = []
else:
nmagic, nh, nrpar, nipar = inpar
rdata = np.fromfile(fid, dtype=np.float32, count=nh * nrpar)
if rdata.size < nh * nrpar:
# handle error
pass
else:
rdata = rdata.reshape(nh, nrpar)
idata = np.fromfile(fid, dtype=np.int32, count=nh * nipar)
if idata.size < nh * nipar:
# handle error
pass
else:
idata = idata.reshape(nh, nipar)
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