Printing zero elements in lines of a sparse matrix

Dear all,
I would like to print the non-zero elements along a give line of a sparse matrix.
In fact I’m trying to find a way to reproduce the behaviour of MATLAB. For example, here’s how a line is printed in MATLAB, it’s very useful:
image
So far, I’ve tried a similar approach with Julia but it seems that it converts the row to a dense row (hence full of zeros) before printing it. Any hint regarding printing sparse matrix elements?
Cheers!

IIUC this is pretty much the normal behaviour in Julia:

julia> using SparseArrays

julia> sp = sprand(10,10,0.1)
10×10 SparseMatrixCSC{Float64, Int64} with 11 stored entries:
  ⋅    ⋅    ⋅   0.27207    ⋅    ⋅    ⋅         ⋅         ⋅          ⋅ 
  ⋅    ⋅    ⋅    ⋅         ⋅    ⋅    ⋅         ⋅         ⋅          ⋅ 
  ⋅    ⋅    ⋅    ⋅         ⋅    ⋅    ⋅         ⋅         ⋅          ⋅ 
  ⋅    ⋅    ⋅    ⋅         ⋅    ⋅    ⋅         ⋅         ⋅          ⋅ 
  ⋅    ⋅    ⋅    ⋅         ⋅    ⋅    ⋅         ⋅        0.0865405  0.9079
  ⋅    ⋅    ⋅   0.246534   ⋅    ⋅   0.743724  0.611045   ⋅          ⋅ 
  ⋅    ⋅    ⋅    ⋅         ⋅    ⋅    ⋅         ⋅        0.684832    ⋅ 
  ⋅    ⋅    ⋅   0.626594   ⋅    ⋅    ⋅         ⋅         ⋅          ⋅ 
  ⋅    ⋅    ⋅   0.541967   ⋅    ⋅    ⋅         ⋅         ⋅          ⋅ 
  ⋅    ⋅    ⋅    ⋅         ⋅    ⋅    ⋅         ⋅        0.330361   0.940725

julia> sp[:,4]
10-element SparseVector{Float64, Int64} with 4 stored entries:
  [1 ]  =  0.27207
  [6 ]  =  0.246534
  [8 ]  =  0.626594
  [9 ]  =  0.541967

Hmmm OK, thanks!
I confirm I get the same result than you from execution within the REPL.
In my case I was running within a script:

 println(typeof(Kuusc))
 println(Kuusc[45,:])

and what comes out is:

and so on
Same with @show.
Maybe, this is because I’m doing this in the middle of a script and not from the REPL directly (and in MATLAB I’m running in the debugger…).

See pretty-printing in Juliaprintln uses show(io, x), but the REPL display uses show(io, "text/plain", x). So do e.g.

show(stdout, "text/plain", Kuusc[45,:])

PS. Please use quoted text, not screenshots.

3 Likes

Thanks a lot, I had no clue about this difference in printing style.
I have tried your suggestion: the printing is indeed different but still not similar to REPL. Here’s what comes out:

840-element view(::SparseMatrixCSC{Float64, Int64}, 43, :) with eltype Float64:
 0.0
 0.0
 0.0
 0.0
 0.0
 0.0
 0.0

I’ve truncated it because it does print all elements of the sparse matrix. Sorry for the screenshots, I’ve partly edited my post above.

Did you use views function in the print or show function? If not, why the type of output is a view?

Thanks for point ting this out. I understood why this was a view. My main function was decorated with the @views macro.
Now, I’ve removed it and the printing suggested by @stevengj works perfectly!
Thanks a lot to all of you!