How to promote a heterogeneous array (Array{Any}) to a homogeneous array with elements of a single common type?

Imagine that, for example, one has a heterogeneous array like

julia> a = {1, 2.2, int32(3), float32(4.4), 5, 6.6}
6-element Array{Any,1}:
 1  
 2.2
 3  
 4.4
 5  
 6.6

for which the single common type of its elements is Float64.

Is there a function or minimalistic command to convert such Any arrays to arrays of elements with a single common type (Array{Float64} for the given example) without having to explicitly write that type or even know it beforehand?

I know that if the brackets [] were used to create the array, one would obtain an Array{Float64} in the first place. However, the question is about the conversion of arrays whose type one cannot control at creation time (e.g., some array comprehensions, arrays read from files, ...).

Upvotes: 3

Views: 886

Answers (3)

JobJob
JobJob

Reputation: 4137

How about:

reshape([a...],size(a)...)

If you're happy with a Vector, you can use simply:

[a...]

Upvotes: 2

I've just discovered that vcat(a...) also works.

However I think @ivarne's solution is preferable, since it explicitly tells what one wants to do.

On the other hand, convert(a...) does not works if it's not defined for the array element types.

Upvotes: 0

ivarne
ivarne

Reputation: 3783

The function you are looking for to convert types is called convert

julia> a = {1, 2.2, int32(3), float32(4.4), 5, 6.6}
f6-element Array{Any,1}:
 1  
 2.2
 3  
 4.4
 5  
 6.6

julia> convert(Array{Float64,1},a)
6-element Array{Float64,1}:
 1.0
 2.2
 3.0
 4.4
 5.0
 6.6

EDIT: I'm not sure I understand your why you would want the behaviour you are asking for, but i would think the solution to the question you ask (not the problem you have!), is:

[promote(a...)...]

Upvotes: 5

Related Questions