The following code
(by @kglr) correctly works if mat1
does not have any row/column headings. However, I am working with a matrix with row/column headings.
How can I adjust the code
given below to remove the zero rows/columns without dropping the headings?
mat1 =
{{0, c1s1, c1s2, c1s3, c2s1, c2s2, c2s3, c3s1, c3s2, c3s3,
c1d1, c1d2, c2d1, c2d2, c2d3, c3d1, c3d2}, {c1s1, 1, 3, 0, 2, 2,
2, 3, 2, 0, 3, 1, 2, 0, 3, 3, 0}, {c1s2, 2, 2, 0, 0, 3, 0, 0, 0,
0, 0, 0, 3, 0, 1, 2, 0}, {c1s3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0}, {c2s1, 2, 1, 0, 0, 2, 0, 2, 3, 0, 2, 3, 1, 0, 2,
2, 1}, {c2s2, 1, 3, 0, 0, 2, 1, 3, 0, 0, 3, 3, 2, 0, 1, 2,
3}, {c2s3, 3, 3, 0, 0, 2, 2, 3, 1, 0, 2, 2, 2, 0, 0, 2, 3}, {c3s1,
1, 2, 0, 0, 2, 0, 3, 0, 0, 1, 0, 1, 0, 2, 3, 1}, {c3s2, 2, 0, 0,
2, 2, 0, 3, 0, 0, 3, 1, 1, 0, 1, 3, 3}, {c3s3, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {c1t, 3, 1, 0, 0, 0, 3, 1, 0, 0, 0,
1, 2, 0, 2, 0, 0}, {c2t, 2, 1, 0, 0, 3, 3, 3, 0, 0, 2, 1, 0, 0,
3, 1, 2}, {c3t, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0}, {va, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 3, 2, 0, 3, 3, 1}};
nonzerorows = Flatten@Position[mat1, Except@{0 ..}, 1, Heads -> False]
nonzerocols = Flatten@Position[Transpose@mat1, Except@{0 ..}, 1, Heads -> False]
mat1NZ = mat1[[nonzerorows, nonzerocols]]
{zerorows, zerocols} = MapThread[
Complement[Range@#@Dimensions[mat1], #2] &, {{First,
Last}, {nonzerorows, nonzerocols}}]
nonzerorows = Flatten@Position[mat1, Except@{_, 0 ..}, 1, Heads -> False]
to match nonzero rows starting with a header. The same thing works for columns. $\endgroup$