JohnPers
JohnPers

Reputation: 21

Is there a fast way to create a bool matrix from another matrix in python?

i would like to know if there is a faster way, not O(n^2), to create a bool matrix out of an integer nxn-matrix.

Example:

given is the matrix:

matrix_int = [[-5,-8,6],[4,6,-9],[7,8,9]]

after transformation i want this:

matrix_bool = [[False,False,True],[True,True,False],[True,True,True]]

so all negative values should be False and all positive values should be True.

The brute force way is O(n^2) and this is too slow for me, too you have any ideas how to make this faster?

Upvotes: 1

Views: 340

Answers (2)

Animeta
Animeta

Reputation: 1363

matrix_int = [[-5,-8,6],[4,6,-9],[7,8,9]]
matrix_bool = [[num > 0 for num in row] for row in matrix_int]

# [[False, False, True], [True, True, False], [True, True, True]]

Upvotes: 1

DataYoda
DataYoda

Reputation: 825

matrix_int = [[-5,-8,6],[4,6,-9],[7,8,9]]

matrix_int = np.array(matrix_int)
bool_mat = matrix_int > 0

result:

array([[False, False,  True],
       [ True,  True, False],
       [ True,  True,  True]])

Upvotes: 3

Related Questions