2
$\begingroup$

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}}]
$\endgroup$
1
  • 1
    $\begingroup$ You can use nonzerorows = Flatten@Position[mat1, Except@{_, 0 ..}, 1, Heads -> False] to match nonzero rows starting with a header. The same thing works for columns. $\endgroup$ Feb 4, 2021 at 20:38

1 Answer 1

2
$\begingroup$

With minimal change in your code:

nonzerorows = Flatten@Position[Rest /@ mat1, Except@{0 ..}, 1, Heads -> False]
{1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 14}
nonzerocols = Flatten@Position[Rest /@ Transpose@mat1, Except@{0 ..}, 1, 
   Heads -> False]
{1, 2, 3, 5, 6, 7, 8, 9, 11, 12, 13, 15, 16, 17}
{zerorows, zerocols} = MapThread[Complement[Range@#@Dimensions[mat1], #2] &, 
  {{First, Last}, {nonzerorows, nonzerocols}}]
 {{4, 10, 13}, {4, 10, 14}}
mat1NZ = mat1[[nonzerorows, nonzerocols]];

MatrixForm[mat1NZ]

enter image description here

MapAt[Highlighted, mat1, 
  Join[Thread[{zerorows, All}], Thread[{All, zerocols}]]] /. 
    Highlighted[Highlighted[a_]] :> Highlighted[a] // MatrixForm

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.