Skip to content

Instantly share code, notes, and snippets.

@rmurphy2718
Created November 28, 2019 23:58
Show Gist options
  • Save rmurphy2718/c989289275fbfd72c0f3e92ab0527b1d to your computer and use it in GitHub Desktop.
Save rmurphy2718/c989289275fbfd72c0f3e92ab0527b1d to your computer and use it in GitHub Desktop.
# Function to create a random permutation matrix of some size
import numpy as np
def r_pmatrix(dim):
"""
Random Permutation Matrix (r_pmatrix)
Create a random permutation matrix P such that PM shuffles the rows of M, for some matrix M
:param dim: dimension of (square) permutation matrix
:return: P, permutation matrix
"""
idx = [xx for xx in range(dim)]
np.random.shuffle(idx)
return np.eye(dim)[idx, :]
if __name__ == "__main__":
# Create a permutation matrix
n = 4
p = r_pmatrix(n)
# Create some n by 2 matrix
a = np.arange(2*n).reshape(n, 2)
# Print a, p, and p @ a
print(f"A =\n{a},\nP=\n{p},\nPA=\n{p @ a}")
# Determinant is always between -1 and 1
print(f"Determinant of P: {np.linalg.det(p)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment