I would like to create a function in Julia that returns two matrices. One way to do that is as follows:
function AB(n,m)
A = rand(n,n)
B = rand(m,m)
return (A = A, B = B)
end
The output looks like this:
julia> AB(2,3)
(A = [0.7001462182920173 0.5485248069467998; 0.8559801029748708 0.8023848206563642], B = [0.7970654693626167 0.08666821253389378 0.45550050243098306; 0.5436826530244554 0.9204593389763813 0.9270606176586167; 0.7055633627200892 0.3702008285594489 0.670758477684624])
The output is not particularly convenient. What I would like to have is something similar to what the function qr() from LinearAlgebra returns. For example:
julia> qr(rand(3,3))
LinearAlgebra.QRCompactWY{Float64,Array{Float64,2}}
Q factor:
3×3 LinearAlgebra.QRCompactWYQ{Float64,Array{Float64,2}}:
-0.789051 -0.570416 -0.228089
-0.213035 -0.0941769 0.972495
-0.576207 0.815939 -0.0472084
R factor:
3×3 Array{Float64,2}:
-0.929496 -0.563585 -0.787584
0.0 0.377304 -0.505203
0.0 0.0 -0.01765
This output is very useful to get at least some idea how these matrices look like.
How can I create a function that returns the matrices like the function qr() from LinearAlgebra?
Any help is much appreciated!
You will need to define your own display method. I present here an abstract approach so you can comfortably reuse it.
We start with a decorator supertype - all structs having this supertype will be nicely displayed.
abstract type Pretty end
And here is the actual implementation:
function Base.display(x::Pretty)
for f in fieldnames(typeof(x))
print(f," is a ")
display(getfield(x,f))
end
end
Let us now see it. You just define any struct, e.g.:
struct S{T} <: Pretty
a::Matrix{T}
b::Matrix{T}
end
And now you have what you need e.g.:
julia> S(rand(2,3), rand(3,2))
a is a 2×3 Matrix{Float64}:
0.40661 0.753072 0.708016
0.371099 0.0948791 0.538046
b is a 3×2 Matrix{Float64}:
0.670715 0.457208
0.353189 0.0248713
0.455794 0.136496
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With