I have a (1-dimensional) numpy array a of length L, filled with numbers from 0 to N-1.
Now, I want to construct a NxL matrix such that in each column c, the a[c]'th entry is 1 and all other entries are 0.
For example, If L=4, N=5 and
a = np.array([1,2,0,4])
then we'd want a matrix
m = np.array([[0,0,1,0],
[1,0,0,0],
[0,1,0,0],
[0,0,0,0],
[0,0,0,1]])
Now, I have the following code:
def vectorize(a, L, N):
m = np.zeros((N, L))
for (i,x) in enumerate(a):
m[x][i] = 1.0
return m
This works fine, but I'm sure there is a faster method using some numpy trick (that avoids looping over a).