Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to broadcast vectors (lists) into tuples in Julia?

Tags:

julia

Is there a generator/iterator function that will turn

a = [1,2]
b = [3,4]

into [(1,3),(2,4)] and

a = 1
b = [3,4]

into [(1,3),(1,4)] using the same expression?

Is there a similar way to create a named tuple such as [(a=1,b=3),(a=1,b=4)]?

like image 814
Alec Avatar asked Apr 07 '20 23:04

Alec


People also ask

How would you define tuple in Julia?

Tuples in Julia are an immutable collection of distinct values of same or different datatypes separated by commas. Tuples are more like arrays in Julia except that arrays only take values of similar datatypes. The values of a tuple can not be changed because tuples are immutable.

What is broadcast in Julia?

The broadcast() is an inbuilt function in julia which is used to broadcast the function f over the specified arrays, tuples or collections.

How do you create a vector in Julia?

Creating a Vector A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])


2 Answers

You can use broadcasting with Julia's dot syntax for this:

julia> tuple.(a, b)
2-element Array{Tuple{Int64,Int64},1}:
 (1, 3)
 (2, 4)

tuple here is a function that just creates a tuple from its arguments.

For NamedTuples you can either call the lower-level constructor directly on tuples with

julia> NamedTuple{(:a, :b)}.(tuple.(a, b))
2-element Array{NamedTuple{(:a, :b),Tuple{Int64,Int64}},1}:
 (a = 1, b = 3)
 (a = 2, b = 4)

where :a and :b are the sorted key names, or equivalently, using an anonymous function:

julia> broadcast((a_i, b_i) -> (a=a_i, b=b_i), a, b)
2-element Array{NamedTuple{(:a, :b),Tuple{Int64,Int64}},1}:
 (a = 1, b = 3)
 (a = 2, b = 4)

Hope that helps!

like image 69
Simeon Schaub Avatar answered Nov 13 '22 13:11

Simeon Schaub


Just broadcast the tuple function.

julia> a = [1,2]; b=[3,4];


julia> tuple.(a,b)
2-element Array{Tuple{Int64,Int64},1}:
 (1, 3)
 (2, 4)

julia> tuple.(1, b)
2-element Array{Tuple{Int64,Int64},1}:
 (1, 3)
 (1, 4)

Second question - broadcast the constructor:

julia> NamedTuple{(:a, :b)}.(tuple.(1, b))
2-element Array{NamedTuple{(:a, :b),Tuple{Int64,Int64}},1}:
 (a = 1, b = 3)
 (a = 1, b = 4)
like image 31
Przemyslaw Szufel Avatar answered Nov 13 '22 13:11

Przemyslaw Szufel