'Storing all nonzero elements of a 2-D array via slicing

for extracting all nonzero elemnts of an one dimentional array, we do the following:

One_D = [1,4,5,0,0,4,7,0,2,6]
One_D[One_D .> 0]

How to do a similar thing for a two or more than 2 dimentinal vectore array?

two_D = [[1,0,2,3,0],[4,0,5,0,6]]

this two_D[two_D .> 0] obviously is incorrect. So, what esle we can try?



Solution 1:[1]

Your two_D is not 2 dimensional, but it is a vector of vectors. You can use then broadcasted filter:

julia> filter.(>(0), two_D)
2-element Vector{Vector{Int64}}:
 [1, 2, 3]
 [4, 5, 6]

If instead your two_D were a matrix like this:

julia> mat = [[1,0,2,3,0] [4,0,5,0,6]]
5×2 Matrix{Int64}:
 1  4
 0  0
 2  5
 3  0
 0  6

You can still use filter but without broadcasting. In this case you will get a flat vector of found elements:

julia> filter(>(0), mat)
6-element Vector{Int64}:
 1
 2
 3
 4
 5
 6

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bogumił Kamiński