read into arrays in Julia

2020-08-13 06:09发布

问题:

I'm relatively new to Julia and am looking for an efficient way to read in from a text file and store each "column" in an array (I have 2 columns, but a general solution would be great as well). For instance, I'd like the input

    1 2
    3 4
    5 6

to be read into two arrays, say, x and y, such that x=[1 3 5] and y=[2 4 6]. I have a working solution (might not compile, just free-handed it), but I feel like there is a more efficient way to do this than to hcat and to read the input file line by line. Any suggestions are much appreciated!

Currently, I am doing the following, more or less:

x=[]; 
y=[]; 
f=open("filename"); 
f=readlines(f); 
for str in f 
     s1, s2= split(str, " "); 
     s1=int(s1); 
     s2=int(s2); 
     x=hcat(x, s1); 
     y=hcat(y, s2);
end

回答1:

Here's a way.

julia> myarray=int(open(readdlm,"mynums.txt"))
3x2 Array{Int32,2}:
 1  2
 3  4
 5  6

julia> x=myarray[:,1]
3-element Array{Int32,1}:
 1
 3
 5

julia> y=myarray[:,2]
3-element Array{Int32,1}:
 2
 4
 6