Deleting row and column from an array

Hello all,

I wanted to remove column and row from an array, but couldn’t find any function to do that. For example, if I want to remove the second row and second column from the following array, how can I do that?

a=[1 0 2; 0 0 0; 3 0 8 ]

Any help regarding this would be appreciated.

2 Likes

Assuming row 2 and column 2 are to be removed,

julia> a=[1 0 2; 0 0 0; 3 0 8 ]
3×3 Array{Int64,2}:
 1  0  2
 0  0  0
 3  0  8

julia> a = a[1:end .!= 2, 1:end .!= 2]
2×2 Array{Int64,2}:
 1  2
 3  8
8 Likes

Thank you very much.

See also dropdims

1 Like

Is there a way to delete several columns and rows ?

Check one way here.

Here are some ways:

julia> a = [10i+j for i in 1:4, j in 0:4]
4×5 Matrix{Int64}:
 10  11  12  13  14
 20  21  22  23  24
 30  31  32  33  34
 40  41  42  43  44

julia> a[[1; 4:end], 3:end]  # Remove rows 2 and 3, colums 1 and 2
2×3 Matrix{Int64}:
 12  13  14
 42  43  44

julia> a[1:end .∉ [[2, 3]], 1:end .∉ [[1, 2]]]
2×3 Matrix{Int64}:
 12  13  14
 42  43  44

julia> using InvertedIndices

julia> a[Not([2,3]), Not([1,2])]
2×3 Matrix{Int64}:
 12  13  14
 42  43  44

# In the last two examples since the removed indices are contiguous we can also use ranges:

julia> a[Not(2:3), Not(1:2)]
2×3 Matrix{Int64}:
 12  13  14
 42  43  44
9 Likes

Possibly a different angle:

a = [10i+j for i in 1:4, j in 0:4]

rmr, rmc = [2, 3], [1, 4]    # rows and cols to remove
n, m = size(a)
ir, ic = BitArray(ones(n)), BitArray(ones(m))
ir[rmr] .= 0; ic[rmc] .= 0
a[ir,ic]
1 Like

Thank you so much. This is what I was looking for