Mohammad Saad
Mohammad Saad

Reputation: 2005

How to convert an array of array to array in Julia?

In the following example I am getting an array of array as an output. I would like to seek suggestion on reducing it to n-element vector.

Example: I have a vector x and then I perform subtraction on first 2 elements of the array which outputs a.

x = Float64.([1,2,3,4,5])
a= x[2,:] - x[1,:]
1-element Vector{Float64}:
 1.0

Now when i collect the following range, it returns array of array, as shown below.

c = collect(range(minimum(x).*a, maximum(x).*a, length=10))
10-element Vector{Vector{Float64}}:
 [1.0]
 [1.4444444444444444]
 [1.8888888888888888]
 [2.333333333333333]
 [2.7777777777777777]
 [3.2222222222222223]
 [3.6666666666666665]
 [4.111111111111111]
 [4.555555555555555]
 [5.0]

I would like to know how may I convert this to a vector, which can output following result?

# Expected result:
10-element Vector{Float64}:
 1.0
 1.4444444444444444
 1.8888888888888888
 2.333333333333333
 2.7777777777777777
 3.2222222222222223
 3.6666666666666665
 4.111111111111111
 4.555555555555555
 5.0

Thanks!!

Upvotes: 3

Views: 269

Answers (2)

David Sainez
David Sainez

Reputation: 6956

In general, you can use a combination of splatting and vcat:

julia> xs = [[1],[2,3],[],[4],[5,6,7]]
5-element Vector{Vector{Any}}:
 [1]
 [2, 3]
 []
 [4]
 [5, 6, 7]

julia> vcat(xs...)
7-element Vector{Any}:
 1
 2
 3
 4
 5
 6
 7

That being said, I would follow Oscar Smith's advice and fix the root problem.

Upvotes: 3

Oscar Smith
Oscar Smith

Reputation: 6378

When constructing a you want a= x[2] - x[1]. Then a will be a scalar, and everything else will behave as expected.

Upvotes: 4

Related Questions