MATLAB: How to convert an image to binary matrix

binarydecimal convertionMATLAB

I have an image P with dimension MxN. How to convert into dimension Mx8N ?
I have used P1 = dec2bin(P);
I am getting 65336×8 but I want 256×2048 how to do so ?

Best Answer

P1 = reshape( permute(reshape( (dec2bin(P, 8) - '0').', 8, size(P,1), size(P,2)), [2 1 3]), size(P,1), size(P,2)*8);
This preserves rows and expands each column to 8 columns -- so like
P(1,1)bit1 P(1,1)bit2 P(1,1)bit3 P(1,1)bit4 P(1,1)bit5 P(1,1)bit6 P(1,1)bit7 P(1,1)bit8 P(1,2)bit1 P(1,2)bit2 and so on
Another approach would be:
P1 = reshape( cat(3, bitget(P,8), bitget(P,7), bitget(P,6), bitget(P,5), bitget(P,4), bitget(P,3), bitget(P,2), bitget(P,1)), size(P,1), size(P,2)*8);
This preserves rows, and places all of the most significant bits together, then the second most significant, then the third most, and so on,
P(1,1)bit1 P(1,2)bit1 P(1,3)bit1 ... P(1,256)bit1 P(1,1)bit2 P(1,2)bit2 .. P(1,256)bit2 P(1,1)bit3 P(1,2)bit3 and so on