How to display a sparse array on the REPL?

If I construct a sparse matrix on the REPL, it can directly display the distribution of non-zero elements of the matrix:

julia> using SparseArrays

julia> sparse(round.(rand(5,5)))
5×5 SparseMatrixCSC{Float64, Int64} with 12 stored entries:
 1.0   ⋅   1.0   ⋅   1.0
  ⋅    ⋅    ⋅   1.0   ⋅
 1.0  1.0  1.0  1.0  1.0
  ⋅   1.0   ⋅   1.0   ⋅
  ⋅    ⋅    ⋅    ⋅   1.0

Now I want to construct a sparse matrix in a .jl script and display it when run the script, for example:

using SparseArrays
a = sparse(round.(rand(5,5)))
println("The sparse matrix is:")
# Print the non-zero elements' distribution on the REPL. How to write?
println("Over.")

How to write?

The REPL uses basically just uses the show method to display output. So you can just use show(x) in your script

The REPL calls display(a), which calls show(stdout, , "text/plain", a) (more precisely, it wraps stdout in an IOContext that limits output.

So, in your script you can either call display(a) or call show(io, "text/plain", a) if you want to output to a particular io stream.

1 Like

But this can’t display the figure:

using SparseArrays
a = sparse(round.(rand(5,5)))
println("The sparse matrix is:")
show(a)
println("Over.")
The sparse matrix is:
sparse([1, 2, 4, 5, 3, 4, 2, 3, 1, 2, 3, 4, 1], [1, 1, 1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 5], [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], 5, 5)Over.

No, this is wrong. The 1-argument show(x) (which is also called by print(x) for most types) calls the 2-argument show(stdout, x). For matrices, this is less verbose than the 3-argument show(stdout, "text/plain", x) called by the REPL’s display.

Summary:

  • display(x) tells the current environment to display x in whatever way it thinks best. This might be a graphical display in something like a Jupyter notebook. By default (e.g. in scripts or in the text REPL), it calls show(io, "text/plain", x) or equivalently show(io, MIME"text/plain"(), x) for an appropriate io stream. (In the REPL, io is an IOContext wrapper around stdout.) The REPR uses display to output the result of an evaluated expression.
  • The 3-argument show(io, ::MIME"text/plain", x) method is verbose pretty-printing of x. By default (if no verbose method is defined for typeof(x)), it calls the 2-argument show(io, x).
  • The 2-argument show(io, x) is the default simple text representation of x. It is what is used by repr(x), and is typically the format you might use to input x into Julia. The 1-argument show(x) calls show(stdout, x).
  • print(x) calls print(stdout, x), which by default calls show(stdout, x). It mainly differs from show when x is a string, where print outputs the raw text but show outputs an escaped string enclosed in quotation marks.
3 Likes

Nice! Professional! Thanks a lot! :handshake: :handshake: