MATLAB: I am writting data from one file to another but not getting the expected data

file

I have a data file called imu_data.bin, I am parsing that file and after parsing getting three outputs inertial_data,time_stamp and raw_data the size of inertial data is 24 bytes for one sample , time stamp is 4 bytes for one sample and for raw data is 28 bytes for one sample. I am trying to write the inertial data after parsing to another file for the purpose I am using the following code
My code is
filename = 'imu_data.bin';
[inertial_data,time_stamps,raw_data]=parse_imu_data(filename);
fid = fopen('test2.bin', 'w');
fwrite(fid, uint8(inertial_data), 'uint8'); % write data
fclose(fid);
As far as I concern after writting the code my output of the file test2.bin should be 24 bytes as I am writing only one sample but I am getting 8944 bytes. Let say it might be reading all the samples then the size of output file must contain nearly 35 thousand bytes as the total sample present in imu_data.bin is 1499.
I don't know why I am getting this pls help.
About my parsing file it is a pre existing file and the result after parsing are also correct and meeting the expected value.

Best Answer

Two things:
fwrite(fid, uint8(inertial_data), 'uint8')
This does not write just one sample, but all the samples.
More importantly, if your inertial_data is indeed 24 bytes (stored as what? uint32?), then teh above uint8() call will map any value above 255 to 255. You should either:
  • not convert the inertial_data. fwrite write it as bytes (uint8) anyway. The only thing you need to be wary off is endianness issues. You can specify the endianness in the call to fopen, or in fwrite.
fwrite(fid, inertial_data) %writes it as bytes anyway
  • convert to uint8 with typecast. This is only useful if you want to keep the data as uint8 for further processing as the above is simpler for just writing:
inertial_data_as_uint8 = typecast(inertial_data, 'uint8');
fwrite(fid, inertial_data_as_uint8);
To see the difference between uint8 and typecast, try the following:
uint8(uint32(512))
typecast(uint32(512), 'uint8')