Posts

Showing posts from April 8, 2019

How to efficiently unroll a matrix by value with numpy?

Image
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box; } 7 I have a matrix M with values 0 through N within it. I'd like to unroll this matrix to create a new matrix A where each submatrix A[i, :, :] represents whether or not M == i. The solution below uses a loop. # Example Setup import numpy as np np.random.seed(0) N = 5 M = np.random.randint(0, N, size=(5,5)) # Solution with Loop A = np.zeros((N, M.shape[0], M.shape[1])) for i in range(N): A[i, :, :] = M == i This yields: M array([[4, 0, 3, 3, 3], [1, 3, 2, 4, 0], [0, 4, 2, 1, 0], [1, 1, 0, 1, 4], [3, 0, 3, 0, 2]]) M.shape # (5, 5) A array([[[0, 1, 0, 0, 0],