On trying to write this answer I reached the frustrating realization that I didn't have an efficient way to delete a list of columns or deeper level components in a simple way as Part
gives.
Given
MatrixForm[m = Partition[Partition[Range[4 4 3], 3], 4]]
I can Delete
rows {2,3}
by
Delete[m, List /@ {2, 3}] // MatrixForm
But to delete the columns or deeper levels I would need to Transpose
twice. For instance using something like this
rDelete[m_, row_, col_] := Delete[
Transpose[
Delete[
Transpose[m]
, List /@ col
]
], List /@ row
]
On the other hand to get a Part
at any level I can easily use
Part[m, All, {1, 4}, {2, 3}] // MatrixForm
Unfortunately, All
and Span
are not available for Delete
.
Question: How can we delete columns or whole higher levels elegantly and efficiently, as we do with Part
?
Answer
You can actually use Part
for that:
ClearAll[delete];
delete[expr_, specs___] :=
Module[{copy = expr},
copy[[specs]] = Sequence[];
copy
];
So that for example
delete[m, All, All, 2]
(*
{
{{1, 3}, {4, 6}, {7, 9}, {10, 12}},
{{13, 15}, {16, 18}, {19, 21}, {22, 24}},
{{25, 27}, {28, 30}, {31, 33}, {34, 36}},
{{37, 39}, {40, 42}, {43, 45}, {46, 48}}
}
*)
Note that this is not exactly equivalent to Delete
in all cases, since sequence splicing is an evaluation-time effect, so the results will be different if you delete inside held expressions - in which case the method I suggested may not work.
Here is a version that would probably be free of the mentioned flaw, but will be slower:
ClearAll[deleteAlt];
deleteAlt[expr_, specs___] :=
Module[{copy = Hold[expr], tag},
copy[[1, specs]] = tag;
ReleaseHold@Delete[copy, Position[copy, tag]]
];
You can test both on say, Hold[Evaluate[m]]
, with the spec 1, All, All, 2
, to see the difference.
Comments
Post a Comment