How to delete arbitrary numbers of columns from a matrix in mathematica
I learned this method long time ago from Mr Wizard answer, it works well. But there are many other ways
a = RandomInteger[25, {9, 11}];
a // MatrixForm
ReplacePart[a, {{_, 4}, {_, 7}} :> Sequence[]];
MatrixForm[%]
The fasted way to do this is to use Part
and construct the indices you need to take using Complement
:
dropColumns[mat_?MatrixQ, columns : {__Integer}] := With[{
columnsToTake = Complement[
Range[Dimensions[mat][[2]]],
columns
]
},
mat[[All, columnsToTake]]
];
a = RandomInteger[25, {9, 11}];
a // MatrixForm
dropColumns[a, {2, 5}] // MatrixForm
A = RandomInteger[25, {9, 11}];
A // MatrixForm
DeleteCol[Matrix_, indexlist_] :=
Block[{internalMatrix = Matrix, i, k = 0,
internallist = SortBy[indexlist, Smaller]},
For[i = 1, i <= Length[internallist], i++,
internalMatrix =
Delete[Transpose[internalMatrix], internallist[[i]] - k];
internalMatrix = Transpose[internalMatrix];
k++;
];
internalMatrix
];
DeleteCol[A, {4, 7}];
% // MatrixForm
DeleteCol[A, {7, 4}];
% // MatrixForm