Remove row of Julia Matrix depending on a function

Viewed 404

There are multiple questions that deal with deleting specific rows in a Julia Matrix if you are given the indexes.

How to delete a row of matrix in julia

Julia: delete rows and columns from an array or matix

What I need is slightly different because I want to delete a row of a Matrix only if all the row's values are zero. Maybe you could generalize my question when you want to delete a row given a specific condition or function. Here it could be that for a row, sum(row .!= 0) == 0

I found the exact transposition of what I need here, for the columns, but I couldn't adapt it for the rows. I tried:

a[vec(mapslices(col -> any(col .!= 0), a, dims = 1)), :]
a[:, vec(mapslices(col -> any(col .!= 0), a, dims = 2))]

Both unsuccessfully.

To give an exemple, I would like to delete row three in the following matrix.

1 0 0 0 0
0 1 0 0 0
0 0 0 0 0
0 0 0 1 0

Finally, I would prefer to create a view of my matrix instead of copying, if possible. That's not mandatory but I think I don't need the copy so it could be better for running times :)

1 Answers

You were almost there:

julia> a = [1 0 0 0 0
            0 1 0 0 0
            0 0 0 0 0
            0 0 0 1 0] ;

julia> a[vec(mapslices(col -> any(col .!= 0), a, dims = 2)), :]
3×5 Array{Int64,2}:
 1  0  0  0  0
 0  1  0  0  0
 0  0  0  1  0

and if you need it:

julia> view(a, vec(mapslices(col -> any(col .!= 0), a, dims = 2)), :)
3×5 view(::Array{Int64,2}, [1, 2, 4], :) with eltype Int64:
 1  0  0  0  0
 0  1  0  0  0
 0  0  0  1  0
Related