Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Initializing numeric arrays of different types

I am trying to build a two element array in Julia, where each sub-array has a different type (one is a vector of Int64s, the other is an array of Float32s).

The code belows automatically converts the element that I want to be an Int64 into a Float32, which is what I don't want:

my_multitype_array = [ collect(1:5), rand(Float32,3) ]

The resulting array automatically converts the Int64s in the first array (defined via collect(1:5)) into a Float32, and the resulting my_multitype_array has type 2-element Array{Array{Float32,1}}. How do I force it to make the first sub-array remain Int64s? Do I need to perhaps pre-define my_multitype_array to be an empty array with two elements of the desired types, before filling it out with values?

And finally, once I do have the desired array with different types, how would I refer to it, when pre-stating its type in a function? See below for what I mean:

function foo_function(first_scalar_arg::Float32, multiple_array_arg::Array{Array{Float32,1}})
       # do stuff
       return
end

Instead of ::Array{Array{Float32,1}}, would I write ::Array{Array{Any,1}} or something?

like image 739
Conor Avatar asked Dec 30 '22 23:12

Conor


1 Answers

I think that the following code matches better what was asked in the question:

julia> a = Union{Array{Int},Array{Float64}}[[1,2,3],rand(2,2)]
2-element Array{Union{Array{Float64,N} where N, Array{Int64,N} where N},1}:
 [1, 2, 3]
 [0.834902264215698 0.42258382777543124; 0.5856562680004389 0.6654033155981287]

This creates an actual data structure which knows that it contains either Float64 or Int arrays.

Some usage

julia> a[1]
3-element Array{Int64,1}:
 1
 2
 3

julia> a[2]
2×2 Array{Float64,2}:
 0.834902  0.422584
 0.585656  0.665403

And manipulating the structure:

julia> push!(a, [1, 1]); #works

julia> push!(a, [true, false]);
ERROR: MethodError: no method matching Union{Array{Float64,N} where N, Array{Int64,N} where N}(::Array{Bool,1})
like image 110
Przemyslaw Szufel Avatar answered Jan 04 '23 00:01

Przemyslaw Szufel