A band matrix is a matrix whose non-zero entries fall within a diagonal band, consisting of the main diagonal and zero or more diagonals on either side of it. (The main diagonal of a matrix \$A\$ consists of all entries \$A_{i,j}\$ for which \$i=j\$.) For this challenge, we will only be considering square matrices.
For example, given this matrix:
1 2 0 0 0
3 4 5 0 0
0 6 0 7 0
0 0 8 9 1
0 0 0 2 3
this is the band:
1 2
3 4 5
6 0 7
8 9 1
2 3
The main diagonal (1 4 0 9 3
) and the diagonals above it (2 5 7 1
) and below it (3 6 8 2
) are the only places non-zero elements are found; all other elements are zero. (Some of the elements in the band may also be zero.)
One nice feature of band matrices is that they can be stored more efficiently: only the elements in the band need to be stored. For example, our 5-by-5 matrix above can instead be stored as a 5-by-3 matrix, where each column represents one diagonal of the original matrix:
0 1 2
3 4 5
6 0 7
8 9 1
2 3 0
Note how the shorter diagonals are padded with zeros: diagonals below the main diagonal are padded at the beginning, while diagonals above the main diagonal are padded at the end.
In this challenge, the band to be stored must be symmetrical about the main diagonal. For example, this matrix:
2 3 4 0 0 0
1 2 3 4 0 0
0 1 2 3 4 0
0 0 1 2 3 4
0 0 0 1 2 3
0 0 0 0 1 2
has this band:
2 3 4
1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3
0 1 2
and so it is stored as:
0 0 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 0
0 1 2 0 0
In this case, one of the diagonals to be stored consists entirely of 0
s, but that diagonal must be included because it is symmetric to the nonzero diagonal consisting of 4
s. (This rule means the output matrix will always have an odd number of columns.)
Challenge
Given an \$N\$-by-\$N\$ band matrix containing nonnegative integers, output/return its rearranged version.
If \$B\$ is the number of diagonals in the band, the resulting matrix will be \$N\$ rows by \$B\$ columns. If you prefer, you may output the result matrix transposed (that is, a matrix of \$B\$ rows by \$N\$ columns).
You may assume that \$B < N\$. In other words, no input that would generate output the same size or larger needs to be handled.
The matrix will always have at least one nonzero entry.
This is code-golf: the goal is to make your code (measured in bytes) as short as possible.
Test cases
1 0
0 1
=>
1
1
1 0 0
0 2 0
0 0 3
=>
1
2
3
0 0 0
0 0 0
0 0 42
=>
0
0
42
1 2 0 0
3 4 5 0
0 6 0 7
0 0 8 9
=>
0 1 2
3 4 5
6 0 7
8 9 0
1 2 0 0 0
3 4 5 0 0
0 6 0 7 0
0 0 8 9 1
0 0 0 2 3
=>
0 1 2
3 4 5
6 0 7
8 9 1
2 3 0
0 1 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
=>
0 0 1
0 0 0
0 0 0
0 0 0
0 0 0
2 3 4 0 0 0
1 2 3 4 0 0
0 1 2 3 4 0
0 0 1 2 3 4
0 0 0 1 2 3
0 0 0 0 1 2
=>
0 0 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 4
0 1 2 3 0
0 1 2 0 0