A1122
A1122

Reputation: 1354

Create a matrix of 0s and 1s based on a vector of 0s and non-0s

Given a vector v=[0, 0, 0, 0, 2, 0, 0, 0, 2.5, 0, 0, 0]

I want to create a matrix with num_rows = np.count_nonzero(v) and num_cols = len(v) of 0s and 1s like the output below. I'm not clear how to generate such a matrix.

output:

[[ 0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.]
 [ 0.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]]

Upvotes: 2

Views: 108

Answers (2)

DJanssens
DJanssens

Reputation: 20689

You could consider the following code, which makes use of the count_nonzero function:

import numpy as np
v=[0, 0, 0, 0, 2, 0, 0, 0, 2.5, 0, 0, 0]
m = np.zeros((np.count_nonzero(v), len(v)))  # create a nxm matrix of zeros where n = #nonzero elements & m = size of vector
nonzero_indexes = np.nonzero(v) # find all nonzero elements - returns the positions
for row_index, col_index in enumerate(nonzero_indexes[0]): # iterate trough positions and update values.
    m[row_index, col_index] = 1
print(m)

Upvotes: 1

omu_negru
omu_negru

Reputation: 4770

Try this:

m = np.zeros((np.count_nonzero(a), len(a)))
row_index = 0
for i in range(len(a)):
    if a[i] != 0:
        m[row_index][i] = 1
         row_index += 1

Upvotes: 3

Related Questions