Given: square matrix, and list which represents the index of rows to be removed, and it also represents at the same time the index of the columns to be removed (it is square matrix, so only one list is needed).
output: the square matrix, with BOTH the rows and the columns in the list removed.
Assume valid list of indices.
This is an example: remove the second and fourth rows and the second and fourth columns from a square matrix.
I asked this question at SO, and more methods are shown there at HTML
Mathematica Three methods are given.
method 1:
(credit for the idea to Mike Honeychurch at stackoverﬂow). It turns out it is easier to work with what we want to keep instead of what we want to delete so that Part[] can be used directly.
Hence, given a list of row numbers to remove, such as
pos = {2, 4};
Start by generating list of the rows and columns to keep by using the command Complement[], followed by using Part[]
a = {{0, 5, 2, 3, 1, 0}, {4, 3, 2, 5, 1, 3}, {4, 1, 3, 5, 3, 2}, {4, 4, 1, 1, 1, 5}, {3, 4, 4, 5, 3, 3}, {5, 1, 4, 5, 2, 0} }; pos = {2, 4}; keep = Complement[Range[Length[a]], pos]; a[[keep, keep]]
Gives
{{0, 2, 1, 0}, {4, 3, 3, 2}, {3, 4, 3, 3}, {5, 4, 2, 0} }
Method 2: (due to Mr Wizard at stackoverﬂow)
ReplacePart[a, {{2},{4},{_, 2},{_, 4}} :> Sequence[]]
Gives
{{0, 2, 1, 0}, {4, 3, 3, 2}, {3, 4, 3, 3}, {5, 4, 2, 0} }
Method 3: (me)
use Pick. This works similar to Fortran pack(). Using a mask matrix, we set the entry in the mask to False for those elements we want removed. Hence this method is just a matter of making a mask matrix and then using it in the Pick[] command.
{nRow,nCol} = Dimensions[a]; mask = Table[True,{nRow},{nCol}]; pos = {2,4}; mask[[All,pos]]=False; mask[[pos,All]]=False; r=Pick[a,mask]/.{}>Sequence[]
gives
Out[39]= {{0,2,1,0}, {4,3,3,2}, {3,4,3,3}, {5,4,2,0}}
Matlab a = [0, 5, 2, 3, 1, 0; 4, 3, 2, 5, 1, 3; 4, 1, 3, 5, 3, 2; 4, 4, 1, 1, 1, 5; 3, 4, 4, 5, 3, 3; 5, 1, 4, 5, 2, 0 ] list=[2 4]; a(list,:)=[]; a(:,list)=[];

a = 0 2 1 0 4 3 3 2 3 4 3 3 5 4 2 0 