Created
June 16, 2023 14:46
-
-
Save turingbirds/bf851676a3ae1886f721daf7e5f0cc03 to your computer and use it in GitHub Desktop.
Extract blocks from block diagonal matrix
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
import numpy as np | |
def extract_block_diagonal_blocks(A): | |
assert A.shape[0] == A.shape[1], "matrix A should be square" | |
N = A.shape[0] | |
A_mirrored = A + A.T # make the matrix symmetric so we only have to check one triangle | |
blocks = [] | |
start = 0 | |
blocksize = 0 | |
while start < N: | |
blocksize += 1 | |
if np.all(A_mirrored[start:start + blocksize, start + blocksize:N] == 0): | |
block = A[start:start + blocksize, start:start + blocksize] | |
blocks.append(block) | |
start += blocksize | |
blocksize = 0 | |
return blocks | |
# Example usage | |
A = np.array([[1, 0, 0, 0], | |
[0, 2, 3, 0], | |
[0, 4, 5, 0], | |
[0, 0, 0, 6]]) | |
block_diagonal_blocks = extract_block_diagonal_blocks(A) | |
# Printing the blocks | |
for i, block in enumerate(block_diagonal_blocks): | |
print(f"A{i+1}:") | |
print(block) | |
print() | |
""" | |
Output: | |
A1: | |
[[1]] | |
A2: | |
[[2 3] | |
[4 5]] | |
A3: | |
[[6]] | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment