12
$\begingroup$

I know that the question of how to remove rows/columns has been asked before, but I am interested in dropping arbitrary rows and arbitrary columns, from a not necessarily square matrix.

So far, I have constructed the function:

RemoveRowsColumns[expr_, a_, b_: Null] := Module[{M},
M = Delete[expr, a];
If[b != Null, M = Delete[Transpose[M], b], 
M = Delete[Transpose[M], a]];
Transpose[M]
];

To remove a columns and b rows. This works for a square matrix provided I am removing the same rows/columns. But If I try and remove, say, rows 1,2,3 and columns 2,3,4 it doesn't give me the right answer. How can I modify it to work correctly?

$\endgroup$
6
$\begingroup$

I don't think you're using Delete correctly. For comparison:

remover[
  m_?MatrixQ,
  rows : {___Integer}, cols : {___Integer}] :=
 Part[
  Delete[m, List /@ rows],
  All, Complement[Range@Length@m[[1]], cols]]

removerr[m_, rows_, cols_] :=
 Module[{r, c},
  r = Complement[Range@Length@m, rows];
  c = Complement[Range@Length@First@m, cols];
  m[[r]][[All, c]]]

SeedRandom[1];

test = RandomInteger[{1, 10}, {5, 3}];

{remove[test, {1, 2, 5}, {2}], removerr[test, {1, 2, 5}, {2}]}

{{{9, 1}, {5, 9}}, {{9, 1}, {5, 9}}}

$\endgroup$
6
$\begingroup$

You need to use UnSameQ instead of Unequal. As Null does not work with ==.

Your function also deleted a row twice.

ClearAll[RemoveRowsColumns];

RemoveRowsColumns[expr_, a_, b_: Null] :=

   Module[{M},

       M = Delete[expr, a];

       If[
          b =!= Null,

          M = Transpose[Delete[Transpose[M], b]],

          M
        ];
      M
  ]

enter image description here

Refactered more

ClearAll[RemoveRowsColumns];
RemoveRowsColumns[expr_, row_, col_: Null] := 

    Module[

        {M = expr},


        If[col === Null,

            M = Delete[M, row],

            M = Delete[M, row];
            M = Transpose[Delete[Transpose[M], col]];

        ]; 

    M]

Note the special syntax when you call it with lists of rows and columns: You have to wrap the row/column numbers in { }(due to Delete):

I will leave it to you to modify RemoveRowsColumns to negate the need for this.

 SeedRandom[1];
(test = RandomInteger[{1, 10}, {5, 3}]) // MatrixForm
RemoveRowsColumns[test, {{1}, {2}, {5}}, {{2}}] // MatrixForm
{{9,1},{5,9}}
$\endgroup$
5
$\begingroup$

The If-statement can be eliminated by choosing the default argument to fit into the same code as a list of parts:

MatrixForm[test = RandomInteger[{0, 9}, {5, 8}]]

RemoveRowsColumns[expr_, a_: {}, b_: {}] := Transpose[Delete[
     Transpose[Delete[expr, Transpose[{a}]]], Transpose[{b}]]]

MatrixForm[RemoveRowsColumns[test, {1, 3, 4}, {3, 4, 5}]]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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