Remove Rows and Columns in a matrix
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}}}
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
]
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}}
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}]]