Reordering matrix with a permutation vector but keeping the original size of matrix Reordering matrix with a permutation vector but keeping the original size of matrix numpy numpy

Reordering matrix with a permutation vector but keeping the original size of matrix


As you found out yourself, the problem is, that index_reorder does only contain the reordered elements.

The solution is, to extend it to a full permutation off all elements. If the elements should stay in place, just write their index at their old position so they will stay.

E.g.:

index_reorder = [2, 4, 0, 5, 1, 3, 7, 8]

should be transformed to:

full_reorder = [2, 4, 0, 5, 1, 3, 7, 8, 6, 9, 10, 11, 12, 13, 14, 15]

Note, that 9->9, 10->10, 11->11.... That way, they are not moved and not lost. There would be other full_reorders thinkable, and their choice only depends on your preference. One, that you might prefer is [2, 4, 0, 5, 1, 3, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]. Here 6->6 and the original permutation is stretched around it.

The changed reorder as given in the first example can be achieved as followed:

all_indices = np.array(range(16))other_indices = np.setdiff1d(all_indices, index_reorder)full_reorder = np.concatenate([index_reorder, other_indices])

And then continue as you have done:

C_temp = np.copy(C_in)C_temp = C_temp[:, full_reorder]C_temp = C_temp[full_reorder, :]