Is there a way to convert a NxM matrix A where
- all values of A are positive integers
to an NxMxL matrix B where
- L = 1 + max(A)
- B[i,j,k] = {1 if k==A[i,j] and 0 otherwise}
using loops I have done the following:
B = np.zeros((A.shape[0],A.shape[1],1+np.amax(A)))
for i in range(A.shape[0]):
for j in range(A.shape[1]):
B[i,j,A[i,j]] = 1
the solution ideally avoids any use of for loops and uses only slicing or indexing or numpy functions
A sample
A:Your code and
B:Defining arrays to index
Bin way that broadcasts withA:Use that indexing to change all the 1s of
Bto 20:the indexes (2,1) and (1,3) pair with (2,3):
There's also newer pair of functions that do that same thing. I'm more familiar with the earlier method