Delimited Files - Writing and reading a complex array

Hi!

My question is very simple, I have a one dimensional complex array, for example:

A = [1.0 + 0.1im, 2.0 + 1.0im, 1.5 + 0.5im];
typeof(A)
Array{Complex{Float64},1}

I want to write this array in a .txt file with DelimitedFiles, so I type the following comand:

open("MyComplexArray.txt", "w") do io
           writedlm(io, A)
       end;

Finally, I want to read the data from MyComplexArray.txt by running:

readArray = readdlm("MyComplexArray.txt", '\t', Complex{Float64}, '\n')
3×1 Array{Complex{Float64},2}:
 1.0 + 0.1im
 2.0 + 1.0im
 1.5 + 0.5im
typeof(readArray)
Array{Complex{Float64},2}

As you can see, this returned a two dimensional complex array with dimension 3x1, and I want a unidimensional array, like the original array A.
I already tried the command readdlm with no delimiters, but gives me an error:

readArray = readdlm("MyComplexArray.txt", Complex{Float64})
ERROR: at row 1, column 1 : ErrorException("file entry \"1.0\" cannot be converted to Complex{Float64}")

Does anyone knows how to avoid this situation? With other data types, such integers or floats this doesn’t happen!

Cheers,
Tiago

Really? readdlm(IOBuffer("2\n3\n4\n"), Int) also returns a 3×1 Array{Int64,2}, for example. (The general principle here is that where possible we want the type of the return value — a 2d array — to not depend on the contents of the data. This is called “type stability.”)

You can always call vec on the result to convert it back to a 1d array efficiently (without copying the data).

1 Like

My bad, I runned with other types and didn’t paid attention to the dimensions, just until I needed to use in my code and got the dimension mismatch error.

Thank you for your suggestion! I will use vec.

Ty