skyork
skyork

Reputation: 7401

Efficient manipulations of binary matrix in numpy

By binary matrix, I mean every element in the matrix is either 0 or 1, and I use the Matrix class in numpy for this.

First of all, is there a specific type of matrix in numpy for it, or do we simply use a matrix that is populated with 0s and 1s?

Second, what is the quickest way for creating a square matrix full of 0s given its dimension with the Matrix class? Note: numpy.zeros((dim, dim)) is not what I want, as it creates a 2-D array with float 0.

Third, I want to get and set any given row of the matrix frequently. For get, I can think of using row = my_matrix.A[row_index].tolist(), which will return a list representation of the given row. For set, it seems that I can just do my_matrix[row_index] = row_list, with row_list being a list of the same length as the given row. Again, I wonder whether they are the most efficient methods for doing the jobs.

Upvotes: 4

Views: 11767

Answers (1)

unutbu
unutbu

Reputation: 880509

To make a numpy array whose elements can be either 0 or 1, use the dtype = 'bool' parameter:

arr = np.zeros((dim,dim), dtype = 'bool')

Or, to convert arr to a numpy matrix:

arr = np.matrix(arr)

To access a row:

arr[row_num]

and to set a row:

arr[row_num] = new_row

is the quickest way.

Upvotes: 7

Related Questions