Reputation: 4137
Say I have:
arr = {"a" "b" "r"}
> 1x3 Array{Any,2}:
> "a" "b" "r"
and I want it to be of type Array{Symbol,2} say.
Upvotes: 1
Views: 918
Reputation: 798
Just since this seems to be the top result when I search for this, I will break out my comment into an answer for visibility.
The accepted answer no longer appears to work. See this link for relevant discussion.
I would recommend using a list comprehension.
Accepted method
arr = ["a" "b" "c"]
1×3 Matrix{String}:
"a" "b" "c"
convert(Array{Symbol}, arr)
ERROR: MethodError: Cannot `convert` an object of type String to an object of type Symbol
Recommended per @DNF comment below.
Symbol.(arr)
1×3 Matrix{Symbol}:
:a :b :c
Possible solution that may not respect shape.
[Symbol(a) for a in arr]
1×3 Matrix{Symbol}:
:a :b :c
Upvotes: 0
Reputation: 12179
There's also
julia> convert(Array{Symbol}, arr)
1x3 Array{Symbol,2}:
:a :b :r
Upvotes: 4
Reputation: 4137
This works:
symarr = reshape(Symbol[arr...],size(arr)...)
Note also if all the elements in the array are of the type you want, you can use:
strarr = reshape([arr...],size(arr)...)
If you're happy with a Vector, you can simply use:
symvec = Symbol[arr...]
strvec = [arr...]
Also here's a macro for fun:
macro convarr(a, t)
:(reshape($t[$a...],size($a)...))
end
@convarr arr Symbol
Note that all the above create new copies of the original Array{Any,2} array
Upvotes: 1