# Converting 1×n array to n-vector

I would like to convert a 1×n array to an n-vector, e.g., `[1 2 3]` to `[1,2,3]`. What is the best way to do so?

My current method is first to convert it to a tuple and then to a vector:

``````julia> VERSION
v"0.7.0"

julia> w = [1 2 3]
1×3 Array{Int64,2}:
1  2  3

julia> [(w...,)...]
3-element Array{Int64,1}:
1
2
3

julia> @btime [(\$w...,)...]
372.714 ns (2 allocations: 144 bytes)
3-element Array{Int64,1}:
1
2
3
``````
• Is there a more efficient way in terms of the number of allocations?
• Is there a more compact way syntactically?

`vec([1 2 3])`

6 Likes
``````julia> w = rand(1,10000000)
1×10000000 Array{Float64,2}:
0.333815  0.882382  0.280182  0.85099  0.0466032  0.958258  …  0.486106  0.573983  0.494289  0.0294783  0.567801

julia> @time [(w...)...];
1.661465 seconds (20.00 M allocations: 539.015 MiB, 53.93% gc time)

julia> @time vec(w);
0.000003 seconds (6 allocations: 240 bytes)
``````
2 Likes

Use `vec`, but be aware that the array and vector share the same memory:

``````julia> w = [1 2 3]
1×3 Array{Int64,2}:
1  2  3

julia> v = vec(w)
3-element Array{Int64,1}:
1
2
3

julia> v = 42
42

julia> w
1×3 Array{Int64,2}:
42  2  3
``````

If you instead want a copy of the data, use `copy(vec(w))`.

3 Likes

In that case, I think `w[:]` would be convenient.

3 Likes

In fact in that case one would get automatically a one-dimensional array (vector).