Q:

Write a NumPy program to convert a given vector of integers to a matrix of binary representation

0

Write a NumPy program to convert a given vector of integers to a matrix of binary representation.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

import numpy as np
nums = np.array([0, 1, 3, 5, 7, 9, 11, 13, 15])
print("Original vector:")
print(nums)
bin_nums = ((nums.reshape(-1,1) & (2**np.arange(8))) != 0).astype(int)
print("\nBinary representation of the said vector:")
print(bin_nums[:,::-1])

Sample Output:

Original vector:
[ 0  1  3  5  7  9 11 13 15]

Binary representation of the said vector:
[[0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1]
 [0 0 0 0 0 0 1 1]
 [0 0 0 0 0 1 0 1]
 [0 0 0 0 0 1 1 1]
 [0 0 0 0 1 0 0 1]
 [0 0 0 0 1 0 1 1]
 [0 0 0 0 1 1 0 1]
 [0 0 0 0 1 1 1 1]]

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now