How can i write a matlab code for making 3 digits pairs from a given binary sequence. and to store that pairs in a array for further use

8 views (last 30 days)
I have a binary string of 27 bits: 111000111000100000010101100. I want to write a matlab code to make pairs of 3 bits to the string length like 111 000 111 000 100 000 101 110. and save these pairs as new symbols in an array like a=[111 000 111 000 100 000 101 110] please help me. Thank you in advance

Accepted Answer

John D'Errico
John D'Errico on 6 Apr 2014
Be willing to learn. Try out the ideas posed in a solution. For example, given a vector of bits b...
b = '111000111000100000010101100';
reshape(b,3,[])'
ans =
111
000
111
000
100
000
010
101
100
See that reshape does create a convenient matrix of bits, where each row here is one of the desired 3 bit strings. Note that very often simple matrices like this are the best way to store such an array, as matrices are so easy to work with.
IF you are going to insist on what is essentially a cell array of bit strings, then a direct mat2cell call is simplest.
mat2cell(b,1,repmat(3,1,numel(b)/3))
ans =
'111' '000' '111' '000' '100' '000' '010' '101' '100'
Again, you will find that the simple flat array was easier to work with though.
  3 Comments

Sign in to comment.

More Answers (2)

Roger Stafford
Roger Stafford on 5 Apr 2014
Consult the documentation for matlab's 'reshape' function at:
http://www.mathworks.com/help/matlab/ref/reshape.html
  1 Comment
John D'Errico
John D'Errico on 6 Apr 2014
Anuj - Try thinking creatively. If b is a bit vector, thus
b = '111000111000100000010101100';
then what would this do?
reshape(b,3,[])'
Perhaps that might indeed have helped you. If you are unwilling to think creatively in this way about how to solve your problem, then what would mat2cell have done here?
Don't shut your mind to solutions as posed. Instead, see what you can learn from them!

Sign in to comment.


Image Analyst
Image Analyst on 6 Apr 2014
Try this. Creates a cell array with 3 character strings in each cell.
s = '111000111000100000010101100'
lastIndex = length(s);
% Extract out 3 at a time and stick into
% one cell of a cell array.
cellIndex = 1;
for index = 1 : 3 : lastIndex
index2 = min(lastIndex, index+2);
sParts{cellIndex} = s(index:index2);
cellIndex = cellIndex + 1;
end
% Display it
celldisp(sParts);
In the command window:
s =
111000111000100000010101100
sParts{1} =
111
sParts{2} =
000
sParts{3} =
111
sParts{4} =
000
sParts{5} =
100
sParts{6} =
000
sParts{7} =
010
sParts{8} =
101
sParts{9} =
100

Categories

Find more on Numeric Types in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!