Last active
November 8, 2017 09:23
-
-
Save numpde/9584779ad235c6ee19be7a6bb87e8af5 to your computer and use it in GitHub Desktop.
Find the rank of a binary matrix over Z/2Z
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Find the rank of a binary matrix over Z/2Z | |
# (conceptual implementation) | |
# | |
# RA, 2017-11-07 (CC-BY-4.0) | |
# | |
# Adapted from | |
# https://triangleinequality.wordpress.com/2014/01/23/computing-homology/ | |
# | |
def binary_rank(M) : | |
# M-pty matrix? | |
if not M.count_nonzero() : return 0 | |
# Find any nonzero entry, i.e. the pivot | |
(p, q) = tuple(a[0] for a in M.nonzero()) | |
# Indices of entries to flip | |
# (Could filter out p and q) | |
I = M[:, q].nonzero()[0] | |
J = M[p, :].nonzero()[1] | |
# Flip those entries | |
for i in I : | |
for j in J : | |
M[i, j] = not M[i, j] | |
# Zero out pivot row p / column q | |
# (Or delete them from the matrix) | |
M[p, :] = 0 | |
M[:, q] = 0 | |
return 1 + binary_rank(M) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment