Perform bit modification in floating point numbers in Matlab

I work at Matlab using non-negative matrix factorization to decompose the matrix into two factors. Using this, I get two double-precision floating-point matrices, B and C.

Results Examples

B(1,1) = 0.118
C(1,1) = 112.035

Now I'm trying to change certain bits in these values, but using the bits function for both values, I get an error because the bit set requires unsigned integers.

I also tried using the dec2bin function, which, as I expected, converts decimal numbers to binary, but returns 0 for B (1,1).

Does anyone know any way to handle bit level floats without losing accuracy?

+5
source share
2 answers

You must study the functions typecastand bitset. (Doc here and here respectively). This allows you to do something like

xb = typecast( 1.0, 'uint64' );
xb = bitset( xb, 10, 1 );
typecast( xb, 'double' );
+6
source

The num2hex and hex2num functions are your friends. (Although not necessarily very good friends, hexadecimal strings are not the best imaginary form for working with binary floating-point numbers. You could break them into, say, 8-inch chunks and convert them to integers.)

From MATLAB docs:

num2hex([1 0 0.1 -pi Inf NaN])

returns

ans =

3ff0000000000000
0000000000000000
3fb999999999999a
c00921fb54442d18
7ff0000000000000
fff8000000000000

and

num2hex(single([1 0 0.1 -pi Inf NaN]))

returns

ans =

3f800000
00000000
3dcccccd
c0490fdb
7f800000
ffc00000
0
source

All Articles