Reputation: 29
suppose i have a vector V=[0 0 1 1 0 1 0 1 1 0]
which contains only 0 & 1 binary digits.presently datatype of vector is double.
I want to write a code in MATLAB which write this vector in a binary file, in such a way that each element of this vectors takes only 1 bit to store in a memory.
For example as the length of vector V is 10, so when i write this vector in binary file it only takes 10 bits or size of binary file is 10 bits, 1 bit for each element.
Is it possible ?
Upvotes: 2
Views: 459
Reputation: 10792
You can use fwrite
to create your binary file and store your data:
%Dummy data:
x = logical([1 0 1 0 1 1 1 0 1 0]) %10x1 logical array
%Create the binary file
fileID = fopen('myfile.bin','w');
%write your data, choose the right data type
fwrite(fileID,x,'logical');
%Close the fileID
fclose(fileID);
%Check the size of your binary file
f=dir('myfile.bin')
the_size=f.bytes
%the_size = 10 bytes
As you can see the binary file has a size of 10 bytes and not 10 bits ! Why ? Because each element of a logical array is 1 byte. There is no 1-bit data type in Matlab. Due to computer architecture accessing a 1-bit data type is much slower than accessing a 1-byte data type and this is why each element of a logical array is 1 byte.
Noticed that you can still write your file bit per bit with ubit1
:
fwrite(fileID,x,'ubit1');
And read those file with:
fo = fopen('myfile.bin','r')
bit=fread(fo,Inf,'ubit1')
But the variable bit
is now a double since there is no ubit1 variable in matlab. Also if mod(number_of_bits_written,8)
is not equal to 0, you won't be able to know where the file end, since your file will have ceil(number_of_bits_written/8)*8
bits, in this case -> 16 bits or 2 bytes with 6 "useless" bits.
Upvotes: 3