Converting an array of integers into a binary representation matrix involves representing each integer as a binary number and organizing these binary numbers into a matrix. The resulting matrix has a row for each input integer and a column for each bit in the binary representation of the integers. In Python, the NumPy library provides several functions that can be used to easily convert an array of integers into a binary representation matrix, which is mentioned below:
1. Using "np.binary_repr()" and "np.vstack()" functions:
- NumPy library is imported and an array is created.
- Then,
np.binary_repr(i, width=4)
is applied, which returns the binary representation of each integer in the vector, zero-padded to a width of4
. - the
list()
function converts the binary string to a list of characters. - The resulting binary vectors are stacked vertically using
np.vstack()
. - Finally, the resulting binary matrix is converted to integers using
astype(int)
.
2. Using "np.binary_repr()" and "np.reshape()" functions:
- the NumPy library is imported and an array is created.
- each integer in
int_vector
is converted to a binary representation with a width of4
using thenp.binary_repr()
function. - The resulting binary vectors are stacked vertically using
np.array()
. - The resulting binary matrix is reshaped to have
4
columns usingnp.reshape()
. - The resulting binary matrix is converted to integers using
astype(int)
.
3. Using "np.bitwise_and()" and "np.reshape()" functions:
- the NumPy library is imported and an array is created.
- Then,
int_vector[:, None]
reshapes the vector to a 2D array with a single column. - Then,
np.bitwise_and(int_vector[:, None], mask)
applies bitwise AND to each element of the vector and the mask to determine which columns to set to1
. - The resulting binary matrix has a shape of
(4,1,4)
, where each row is a 2D array with a single row and4
columns. - Here,
binary_matrix.reshape(-1, 4)
flattens the binary matrix to a 2D array with4
columns and a number of rows that is automatically calculated based on the original shape. - Finally, the resulting binary matrix is converted to integers using
astype(int)
.