Writing complex-entried vectors to text files

How do I write a vector with Complex{Float64} type entries into a text file so that I may read it later ? writedlm() does not seem to work :

t = rand(Complex{Float64}, 3); 
writedlm("t.txt", t, ""); 
t2 = readdlm("t.txt")
3×3 Array{Any,2}:
 0.431139  "+"  "0.6332339101461475im"
 0.589629  "+"  "0.03915758218748211im"
 0.259354  "+"  "0.22444070781836611im"

There is no standard for representing complex numbers in delimited files. I would just split them, eg

writedlm("/tmp/t.txt", hcat(real.(t), imag.(t)))
u = readdlm("/tmp/t.txt") |> x -> Complex.(x[:, 1], x[:, 2])
t == u # true
3 Likes

It was useful to learn about this notation, where can I learn more about the use of the | separator in readdlm ? I have found a solution using serialize .
On a separate note, would you consider it worthwhile to enable reading and writing f Complex valued arrays using readdlm ? Serializing makes the file unreadable using text editors.

I think you may misunderstand, the | above is in the |> operator, which just applies that anonymous function.

No, I think that delimited formats should be kept simple. They are not equipped to support any kind of structure.

I would suggest you explore JSON-based solutions: some of them can serialize structures, and they are plain text. Look at the JSON packages in the registry.

2 Likes

It works as long as you tell readdlm that you want to read complex numbers:

julia> t2 = readdlm("t.txt", ',', ComplexF64)
3×1 Array{Complex{Float64},2}:
 0.0019004307849912472 + 0.42546410422261594im
     0.710874046364316 + 0.12131057843728388im
     0.483710505641759 + 0.054679671784845896im

(Julia supports the formats X+Yim, X+Yi, and X+Yj: Julia, Matlab, and Python formats.)

2 Likes