Conversion from string to matrix

I saved a complex matrix to a text file, e.g. ComplexF64[1.0 + 1.0im 1.0 + 0.0im; 5.0 + 0.0im 0.0 + 0.0im] but struggle to read it again. Is there an easy way to parse this?

Technically, you could do:

julia> eval(Meta.parse("ComplexF64[1.0 + 1.0im 1.0 + 0.0im; 5.0 + 0.0im 0.0 + 0.0im]"))
2×2 Matrix{ComplexF64}:
 1.0+1.0im  1.0+0.0im
 5.0+0.0im  0.0+0.0im

However, you should be aware that parsing and evaluating arbitrary code is dangerous, especially if the strings come from an untrusted source.

1 Like

Depends on your goals. If you want to persist data so that it can be used later, and you don’t care about human readability, then the easiest option is to use the Serialization library:

julia> using Serialization

julia> serialize("cpx.bin", ComplexF64[1.0 + 1.0im 1.0 + 0.0im; 5.0 + 0.0im 0.0 + 0.0im])
64

julia> deserialize("cpx.bin")
2×2 Matrix{ComplexF64}:
 1.0+1.0im  1.0+0.0im
 5.0+0.0im  0.0+0.0im

If, on tthe other hand, you want to preserve human readability, you can use eval to parse the string:

julia> write("cpx.txt", string(ComplexF64[1.0 + 1.0im 1.0 + 0.0im; 5.0 + 0.0im 0.0 + 0.0im]))
60

julia> eval(Meta.parse(read("cpx.txt", String)))
2×2 Matrix{ComplexF64}:
 1.0+1.0im  1.0+0.0im
 5.0+0.0im  0.0+0.0im

Note that calling eval on unsantiized strings from untrusted sources is dangerous, so only use this method if you are 100% certain that the contents of the text file are safe.

5 Likes

You can also just use comma-delimited text, e.g. via the DelimitedFiles library or several other libraries:

julia> using DelimitedFiles

julia> writedlm("cpx.csv", [1.0 + 1.0im 1.0 + 0.0im; 5.0 + 0.0im 0.0 + 0.0im], ',')

julia> readdlm("cpx.csv", ',', ComplexF64)
2×2 Matrix{ComplexF64}:
 1.0+1.0im  1.0+0.0im
 5.0+0.0im  0.0+0.0im

These have the advantage of being more human-readable and more portable across Julia versions.

See also the discussion thread: Saving an array of complex numbers

5 Likes