1

How do I convert characters from a file, e.g. 'hello' to a binary matrix like this:

[1  1   0  1  1  0  0 0  1 0 .......]

where each column of the matrix has only a 1 bit value that is 0 or 1.

All I have done so far is converted the string into the matrix of binary where each column has 7 bits of binary.

Example: 'hello'

1 1 0 1 1 0 0 0 1 0

1
  • What is the standard of conversion? ASCII? Commented May 17, 2013 at 15:17

1 Answer 1

1

You need a combination of dec2bin and str2num:

First, convert your input into a binary representation:

WORD = 'hello'; 

WORD_BINARY = dec2bin(WORD,7) % The 7 gives the number of bits

This results in:

WORD_BINARY =

1101000
1100101
1101100
1101100
1101111

This is a string, which now has to be turned into a vector:

for i=1:size(WORD_BINARY,1)
    for j=1:size(WORD_BINARY,2)
        WORD_OUTPUT(1,(i-1)*size(WORD_BINARY,2)+j) = str2num(WORD_BINARY(i,j))
    end
end

WORD_OUTPUT in this case is a <1x40> vector, starting with:

WORD_OUTPUT = 

[ 1     1     0     1     0     ...  

Edit

If you do not want two for loops, you can use reshape first (but be aware, that reshape orders by column, not row):

WORD = 'hello'; 

WORD_BINARY = reshape(dec2bin(WORD,7)',1,[]);
% note the <'> after the dec2bin, to transpose the matrix

for j=1:size(WORD_BINARY,2)
    WORD_OUTPUT(1,j) = str2num(WORD_BINARY(1,j));
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.