Converting double values file to 2 byte per sample.

Hi,
I have a .txt file with 128 x 11900 vlaues. These values are doubles ranging from -0.00023462 to +1.0719. I need to convert them to 2 bytes per sample and store in a .bin file. I am not getting how to do it. I tried using the 'fread' function of matlab but all I am able to do is convert each sample to 8 bytes(double precision). Is there a way I can convert each sample into 2 bytes each?

 채택된 답변

Walter Roberson
Walter Roberson 2020년 7월 16일
two_bytes = uint16(floor(YourMatrix/1.636E-5)+15);
and fwrite() as uint16 .
reconstructed = (double(two_bytes) - 15) * 1.636E-5
the reconstruction error can be up to 1.636E-5 . You can reduce the average reconstruction error by using round() instead of floor(), but then you have to work on the boundary condition (the +15 or -15) (though there happens to be just enough slack room in the representation so that it is not a problem.)

댓글 수: 4

Yes, it solved my problem. But why 15?
Divide the difference between the max and min by the number of different 16 bit values, 65536. You get a number for the difference between adjacent quantified samples, but it is not a convenient number to put in code, so tweak it to be a slightly smaller "nice" number, delta.
Now for any one sample, the representation in 2^16th units is floor of (the sample divided by delta). Apply that to the lower bound of your data and you get -15. Your data is quantized between -15*delta and 65519 times delta.
At this point you could use a signed representation but it is a waste to effectively devote an entire bit for the matter of whether the quantized value is in the range -15 to -1 and you would need to use a delta twice as large. Easier to add 15 to the quantized value to shift to the range 0 to 65534 .
If you round instead of floor then the shifted quantized value becomes the range 1 to 65535 which is fine.
"Now for any one sample, the representation in 2^16th units is floor of (the sample divided by delta). Apply that to the lower bound of your data and you get -15"
you mean -14? floor(-0.00023462/1.636E-5)
No, I mean -15
>> floor(-0.00023462/1.636E-5)
ans =
-15

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

James Tursa
James Tursa 2020년 7월 16일

0 개 추천

If you want a two byte floating point representation you can use half precision. E.g.,
This is one of the standard floating point formats, but will result in less precision than Walter's method because some of the bits are used for sign and exponent.

카테고리

도움말 센터File Exchange에서 Numeric Types에 대해 자세히 알아보기

태그

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by