Home > Blockchain >  Read an Array of Arrays separated by blank lines in Julia
Read an Array of Arrays separated by blank lines in Julia

Time:11-13

I have an array of arrays stored as blocks of tabular data in a textfile. The blocks have different number of rows but the same number of columns. Like this:

7 9
9 9

7 1
1 1
3 3

4 1

And so on. I would like to read them in Julia and to end with an array of arrays, or an array of 2 dimensional arrays, like this:

a=[ [7, 9; 9 ,9], [7, 1; 1, 1 ; 3 3 ]] ...

I am trying with different ideas with do syntax, but I am being not very succesfull yet.

aux=[]
open("cell.dat") do f
    aux=[]
    aux2=[]
    for line in eachline(f)
        if line != ""
            aux2=vcat(aux2,line)
        else
            print("tuabuela")
            aux=vcat(aux,aux2)
            print(aux, aux2)
            aux2=[]
        end
    end
end

I end with an empty array!

CodePudding user response:

There are many ways to do it. Suppose the file is not huge and you have read your file to String called dat:

dat="""7 9     
9 9            
               
7 1            
1 1            
3 3            
               
4 1"""         

In that case you can do:

julia> readdlm.(IOBuffer.(split(dat,"\n\n")))
3-element Vector{Matrix{Float64}}:
 [7.0 9.0; 9.0 9.0]
 [7.0 1.0; 1.0 1.0; 3.0 3.0]
 [4.0 1.0]
  • Related