Remove zero from Matrix

Hello, I have a matrix of the following form

20×3 Matrix{Float64}:
 0.0         0.0          0.0
 0.0         0.0          0.0
 9.94549e-6  1.0e-5      -6.21704e-6
 0.0         0.0          0.0
 0.0         0.0          0.0
 1.01235e-5  2.78136e-5  -6.45014e-6
 0.0         0.0          0.0
 0.0         0.0          0.0
 0.0         0.0          0.0
 0.0         0.0          0.0
 0.0         0.0          0.0
 0.0         0.0          0.0
 0.0         0.0          0.0
 9.97805e-6  1.0e-5      -7.118e-6
 0.0         0.0          0.0
 0.0         0.0          0.0
 0.0         0.0          0.0
 0.0         0.0          0.0
 9.61955e-6  1.0e-5      -5.62205e-6
 0.0         0.0          0.0

How can i remove all zeros type of 0.0 from matrix?
I need to build the second and third columns without zeros 0.0, and all I could come up with was to remove the zeros. I using CairoMakie for plot
Thank your for help

I’m not sure I understand what you’re after. You might need to provide an example of your desired output. But here are a couple of related options assuming your matrix is z

# for each column, return the nonzero values
julia> [filter(!iszero,c) for c in eachcol(z)]
3-element Vector{Vector{Float64}}:
 [9.94549e-6, 1.01235e-5, 9.97805e-6, 9.61955e-6]
 [1.0e-5, 2.78136e-5, 1.0e-5, 1.0e-5]
 [-6.21704e-6, -6.45014e-6, -7.118e-6, -5.62205e-6]

# remove rows that are entirely zero
julia> permutedims(stack(filter(!iszero,eachrow(z))))
4×3 Matrix{Float64}:
 9.94549e-6  1.0e-5      -6.21704e-6
 1.01235e-5  2.78136e-5  -6.45014e-6
 9.97805e-6  1.0e-5      -7.118e-6
 9.61955e-6  1.0e-5      -5.62205e-6

# remove zeros from each column, then reassemble (assuming the shortened columns have the same lengths)
julia> reduce(hcat, [filter(!iszero, c) for c in eachcol(z)])
4×3 Matrix{Float64}:
 9.94549e-6  1.0e-5      -6.21704e-6
 1.01235e-5  2.78136e-5  -6.45014e-6
 9.97805e-6  1.0e-5      -7.118e-6
 9.61955e-6  1.0e-5      -5.62205e-6
3 Likes

x[ x[:,1].!=0, :], asssuming you want to remove all zeros and each column has zeros on the same position.

2 Likes

Thank you, this is exactly what I needed

This is nice, however I’ll note that some improvements are possible:

  1. avoid the unnecessary copy: x[(@view x[:,1]) .!= 0, :]
  2. correct for indexing bases other than one: x[(@view x[:,begin]) .!= 0, :]
  3. using iszero is arguably prettier than comparing against a literal: x[(!iszero).(@view x[:,begin]), :]
1 Like

a little pulled by the hair, but there would also be this

using SparseArrays
reshape(SparseArrays.nzvalview(sparse($m)),:,3)
reshape(nonzeros(sparse($m)),:,3)
1 Like