 # How to make 1×n Array{String, 2} from n-element Array{String, 1}?

I am using Plots and it requires to be set labels as 1×n Array{String, 2} but I want to make the labels automatically. I can get n-element Array{String, 1} but I cannot find how to convert this to 1×n Array{String, 2}. Can anyone help?

``````julia> reshape(["a","b","c"], 1, :)
1×3 Array{String,2}:
"a"  "b"  "c"
``````
2 Likes

I stuck this for a long. Thanks a lot!

or `hcat(x...)` which I find easier to remember (it is a bit slower though).

There’s also `permutedims`:

``````
julia> sa = ["a","b","c"]
3-element Array{String,1}:
"a"
"b"
"c"

julia> permutedims(sa)
1×3 Array{String,2}:
"a"  "b"  "c"

``````

`permutedims(sa)` seems to be about 5x faster than `reshape(sa, 1, :)`, though the difference probably doesn’t matter in this case.

2 Likes

I cant permutedims. What version is your Julia? I’m using 0.6.2.

``````julia> sa = ["a", "b", "c"]
3-element Array{String,1}:
"a"
"b"
"c"

julia> permutedims(sa)
ERROR: MethodError: no method matching permutedims(::Array{String,1})
Closest candidates are:
permutedims(::Union{Base.ReshapedArray{T,N,A,MI} where MI<:Tuple{Vararg{Base.MultiplicativeInverses.SignedMultiplicativeInverse{Int64},N} where N} where A<:Union{DenseArray, SubArray{T,N,P,I,true} where I<:Tuple{Union{Base.Slice, UnitRange},Vararg{Any,N} where N} where P where N where T}, DenseArray{T,N}, SubArray{T,N,A,I,L} where L} where I<:Tuple{Vararg{Union{Base.AbstractCartesianIndex, Int64, Range{Int64}},N} where N} where A<:Union{Base.ReshapedArray{T,N,A,MI} where MI<:Tuple{Vararg{Base.MultiplicativeInverses.SignedMultiplicativeInverse{Int64},N} where N} where A<:Union{DenseArray, SubArray{T,N,P,I,true} where I<:Tuple{Union{Base.Slice, UnitRange},Vararg{Any,N} where N} where P where N where T} where N where T, DenseArray} where N where T, ::Any) at multidimensional.jl:1292
permutedims(::AbstractArray, ::Any) at permuteddimsarray.jl:116
``````

Huh, it’s a v0.7 change apparently:

permutedims(m::AbstractMatrix) is now short for permutedims(m, (2,1)), and is now a more convenient way of making a “shallow transpose” of a 2D array. This is the recommended approach for manipulating arrays of data, rather than the recursively defined, linear-algebra function transpose. Similarly, permutedims(v::AbstractVector) will create a row matrix (#24839).

It was on 0.7 that I tried that, I too get this error on 0.6. `permutedims` on 0.6 doesn’t seem to have a way of changing a 1-D array into 2-D, so reshape is probably the way to go.

1 Like

This short thread had been so educational. I didn’t know about permutedims (well, I did at one point and then forgot), and I also didn’t know you could do `:` in reshape - that’s great!