Search code examples
julia

Julia: How to pretty print an array?


a= zeros(4,4)

Print a like this

> 4×4 Array{Float64,2}:
>  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

but println(a) prints like this

[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]

How can I "print" a in the former way within a function? I want it fo debugging purposes.


Solution

  • Use display(x).

    Let me comment here on what is going on here. A key difference is between show(io, x) and show(io, mime, x), as you can see in the docs:

    help?> show(stdout, a) show([io::IO = stdout], x)

    Write a text representation of a value x to the output stream io. New types T should overload show(io::IO, x::T). The representation used by show generally includes Julia-specific formatting and type information, and should be parseable Julia code when possible.

    repr returns the output of show as a string.

    To customize human-readable text output for objects of type T, define show(io::IO, ::MIME"text/plain", ::T) instead. Checking the :compact IOContext property of io in such methods is recommended, since some containers show their elements by calling this method with :compact => true.

    So:

    • show without MIME writes a text representation of an object,
    • show with MIME tries to produce a human-readable format.

    Now print(io, x) fallsback to show(io, x) as you can see here:

    function print(io::IO, x)
        lock(io)
        try
            show(io, x)
        finally
            unlock(io)
        end
        return nothing
    end
    

    and display by default in REPL falls back to show(io, mime, a):

    function display(d::REPLDisplay, mime::MIME"text/plain", x)
        io = outstream(d.repl)
        get(io, :color, false) && write(io, answer_color(d.repl))
        if isdefined(d.repl, :options) && isdefined(d.repl.options, :iocontext)
            # this can override the :limit property set initially
            io = foldl(IOContext, d.repl.options.iocontext,
                       init=IOContext(io, :limit => true, :module => Main))
        end
        show(io, mime, x)
        println(io)
        nothing
    end
    

    (in both cases I have copied definitions from the Base, that you end up getting using default print(a) and display(a) operations - skipping methods that are called in the process)

    You can find more information about it here in the Julia manual.

    So in your case - as Jun Tian suggested you can use display. Also just to show that this all falls back to show:

    julia> a = zeros(4,4);
    
    julia> show(stdout, a)
    [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]
    julia> show(stdout, "text/plain", a)
    4×4 Array{Float64,2}:
     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