out = np.zeros([len(labels_i), len(labels_j)])
for i in range(len(labels_i)):
    for j in range(len(labels_j)):
        out[i, j] = np.prod([m[labels_i[i][k], labels_j[j][k]] for k in
            range(n)])
return out
Numpy/Python: Efficient matrix as multiplication of cartesian product of input matrix