Bit slices
Blog reader Kathirvel wanted to know more about the MATLAB default image and how it was formed.
I'll show briefly how it was done, using a small magic square and a Pascal matrix.
m = magic(3)
m = 8 1 6 3 5 7 4 9 2
p = pascal(3)
p = 1 1 1 1 2 3 1 3 6
The values of these two matrices can be stored in a single matrix by using bitshift and bitor. Let's let the magic square occupy the least-significant four bits, and let the Pascal matrix occupy the next four. We need to bit-shift the values in the Pascal matrix by four bits, and then bit-or the result with the magic square.
p_shifted = bitshift(p, 4)
p_shifted = 16 16 16 16 32 48 16 48 96
combined = bitor(m, p_shifted)
combined = 24 17 22 19 37 55 20 57 98
Look at the 8-bit binary representation of combined(3,3):
dec2bin(combined(3,3), 8)
ans = 01100010
Compare that with the 4-bit binary representation of m(3,3) and p(3,3):
dec2bin(m(3,3), 4)
ans = 0010
dec2bin(p(3,3), 4)
ans = 0110
You can see how combined(3,3) contains the bits from both m(3,3) and p(3,3). The original values can be recovered from combined by using bitshift and bitand.
Check out Loren's Art of MATLAB post today - it has more information about using MATLAB bit functions.
Comments
To leave a comment, please click here to sign in to your MathWorks Account or create a new one.