Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of the dot prefix for an arbitrary function?

Tags:

julia

Julia allows me to do elementwise binary operators on arrays/matrices with .:

[1 2 3] .+ [3 2 1]
[1 2 3] .> [3 2 1]

Is there a standard way to apply an arbitrary function f elementwise to a pair of arrays?

like image 631
Qwertie Avatar asked Feb 07 '15 20:02

Qwertie


People also ask

What does the dot mean in R?

It is just a variable name. R variables names can consist of alphanumerics and dot (.)

What does three dots mean in R?

In technical language, this is called an ellipsis. And it means that the function is designed to take any number of named or unnamed arguments. By the way, the ellipsis is not a specialty of R. Other programming languages have the same or a similar concept.

What does def mean in Python?

def is the keyword for defining a function. The function name is followed by parameter(s) in (). The colon : signals the start of the function body, which is marked by indentation. Inside the function body, the return statement determines the value to be returned.


1 Answers

If you just want to apply a binary function to each pair of values from two lists, you can use map:

f(x,y) = 2x - y^2

julia> map(f, [1, 2, 3], [3, 2, 1])
3-element Array{Int64,1}:
 -7
  0
  5

The .+ and .> operators also have the additional behavior that singleton dimensions are broadcast, like so:

julia> [1, 2, 3] .+ [-1 -2 -3]
3x3 Array{Int64,2}:
 0  -1  -2
 1   0  -1
 2   1   0

julia> rand(3,4) .+ [1, 2, 3]
3x4 Array{Float64,2}:
 1.73798  1.84132  1.12923  1.30192
 2.10961  2.17835  2.52779  2.3028
 3.16457  3.04659  3.67604  3.08869

julia> rand(3,4) .+ [1 2 3 4]
3x4 Array{Float64,2}:
 1.40294  2.31384  3.34001  4.60027
 1.13289  2.99275  3.50606  4.51049
 1.31486  2.7585   3.64655  4.59647

If you also want this kind of behavior, you can use the broadcast function:

julia> broadcast(f, [1 2 3], [3, 2, 1])
3x3 Array{Int64,2}:
 -7  -5  -3
 -2   0   2
  1   3   5
like image 110
StefanKarpinski Avatar answered Sep 18 '22 20:09

StefanKarpinski