问题
How can I delete one or more rows and/or columns from an array?
回答1:
Working with:
julia> array = [1 2 3 4; 5 6 7 8; 9 10 11 12; 13 14 15 16]
4×4 Array{Int64,2}:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
To delete a single row (here row 2):
julia> newarray = array[1:end .!= 2, :]
3×4 Array{Int64,2}:
1 2 3 4
9 10 11 12
13 14 15 16
To delete a single column (here column 3):
julia> newarray = array[:, 1:end .!= 3]
4×3 Array{Int64,2}:
1 2 4
5 6 8
9 10 12
13 14 16
To delete a single row and a single column (here row 2, column 3):
julia> newarray = array[1:end .!= 3, 1:end .!= 3]
3×3 Array{Int64,2}:
1 2 4
5 6 8
13 14 16
To delete multiple rows (here rows 2, 4):
julia> newarray = array[setdiff(1:end, (2,4)), :]
2×4 Array{Int64,2}:
1 2 3 4
9 10 11 12
To delete multiple columns (here columns 2, 4):
julia> newarray = array[:, setdiff(1:end, (2,4))]
4×2 Array{Int64,2}:
1 3
5 7
9 11
13 15
To delete a single row and multiple columns (here row 4 and columns 3, 4):
julia> newarray = array[1:end .!= 4, setdiff(1:end, (3,4))]
3×2 Array{Int64,2}:
1 2
5 6
9 10
# or
julia> newarray = array[setdiff(1:end, 4), setdiff(1:end, (3,4))]
3×2 Array{Int64,2}:
1 2
5 6
9 10
# or
julia> newarray = array[setdiff(1:end, (4,)), setdiff(1:end, (3,4))]
3×2 Array{Int64,2}:
1 2
5 6
9 10
To delete multiple rows and columns (here rows 1, 2 and columns 3, 4):
julia> newarray = array[setdiff(1:end, (1,2)), setdiff(1:end, (3,4))]
2×2 Array{Int64,2}:
9 10
13 14
来源:https://stackoverflow.com/questions/58033504/julia-delete-rows-and-columns-from-an-array-or-matix