# How to represent a binary number in a matrix in Matlab?

This is a fairly simple question but my Matlab knowledge is still very limited.

I want to take a given binary number (or rather, a bistring) of length $mn$ and generate an $m \times n$ matrix whose entries correspond to the bit values.

For example, if the given bitstring is $b = 1001110101$ (which is the binary value of the base-10 number 629), and since $b$ has length 10 which can be represented as 2*5, I am looking for a sequence of Matlab commands to convert $b$ to this matrix $A$:

$$A = \begin{pmatrix} 1 & 0 & 0 & 1 & 1 \\ 1 & 0 & 1 & 0 & 1 \end{pmatrix}.$$

I have come close in the past using cell and string commands, but I never actually seem to get the matrix in the proper sense that I can compute things like $AA'$.

In case it helps, my application program will always generate bitstrings that are of a given length $b = mn$. That is, $m$ and $n$ are known so there is no guesswork when it comes to the size of the desired matrix.

## 1 Answer

There is a MATLAB function in the Communications Toolbox called de2bi that will convert a decimal number to a binary vector. Once you get the binary vector, you can reshape it. The reshape command preserves columnwise ordering, so you might need to transpose the dimensions (i.e., generate an $n$ by $m$ matrix) and then transpose the resulting reshaped matrix (via transpose) operator.

If you don't have the Communications Toolbox, you could probably emulate de2bi using built-in commands. If x is your decimal number, then b = num2str(dec2bin(x.))-'0' will probably work, following this MathWorks Central post. (I haven't tested this function, however, because I don't have a personal MATLAB license.)