0

I know bin(Z) in python returns a binary equivalent for the integer Z but what I couldn't figure out is how to apply bin to every element of an integer matrix in python.

input(2x3)
matrix[[1, 1, 2],[3, 5, 8]]

output(2x3) with 8 bits
matrix[[00000001, 00000001, 00000010],[00000011, 00000101, 00001000]]
falsetru
  • 357,413
  • 63
  • 732
  • 636
Nuelsian
  • 501
  • 7
  • 18

3 Answers3

0

Using numpy's binary_repr() you can convert a given integer to its binary representation as the name indicates. The width parameter enables for outputs of given length (8 in this case). However, applying this to matrices or arrays will yield the issue of missing leading zeros. This can be tackled by either using strings in the binary representation or the use of zfill() as demonstrated here. So giving examples of possible solutions:

import numpy as np

data = np.random.randint(0,100,(2,3), dtype=int)
print(data)
n,m = data.shape
data_bin = np.zeros((n, m), dtype=int)
for i in range(n):
    for j in range(m):
        data_bin[i, j] = np.binary_repr(data[i, j], width=8)
print(data_bin)

data_bin_str = np.zeros((n, m), dtype='|S8')
for i in range(n):
    for j in range(m):
        data_bin_str[i, j] = str(np.binary_repr(data[i, j], width=8))
print(data_bin_str)

Note the loop-setup as binary_repr() has no array support as far as i know (see here).

Community
  • 1
  • 1
mmensing
  • 311
  • 1
  • 7
0

you should be able to use list comprehensions to do it.

[[bin(x) for x in y] for y in matrix]

Ewe
  • 86
  • 2
  • It doesn't. Error msg : only integer arrays with one element can be converted to an index – Nuelsian Mar 21 '17 at 20:43
  • That was for a 2D list, I see now that you're using numpy.matrix. `numpy.matrix([[bin(x) for x in y] for y in matrix.tolist()]) ` – Ewe Mar 26 '17 at 22:03
0

for a given input matrix: input_matrix

matrix([[bin(int(entry))[2:].zfill(8) for entry in row_vector]for row_vector 
in array(input_matrix)])

examples.

input_matrix = matrix([[1, 1, 2],[3, 5, 8]])

output = matrix([['00000001', '00000001', '00000010'],
                 ['00000011', '00000101', '00001000']], dtype='|S8')
Nuelsian
  • 501
  • 7
  • 18