A simple way to perform calculations for every element of the vector with each of elements of this vector

Viewed 315

For example, for each element of a vector, I want to calculate the sum of the residuals with other elements of this vector. This works correctly for one element:

a = [1, 2, 5, 7, 8, 22]
f(x) = sum(abs.(x .- a))
f(2)
Out: 35

But if apply this function to all elements using map(), Julia return an error:

map(a, f)
Out: "MethodError: no method matching iterate(::typeof(f))"

In R this is very easy to get using sapply():

a = c(1, 2, 5, 7, 8, 22)
sapply(a, function(x) sum(abs(x - a)))
Out: 39 35 29 29 31 87

Is there an equally elegant way to do this in Julia?

3 Answers

Just vectorize over f:

julia> f.(a)
6-element Array{Int64,1}:
 39
 35
 29
 29
 31
 87

The function map takes the function that it applies to a collection as its first argument. I.e. you can write

map(f, a)

Note that to get even closer to your R syntax, map() (and julia in general) allows you to specify an anonymous function after the map call which is used as map's first argument, so:

julia> map(a) do x
       sum(abs.(x .- a))
       end
6-element Array{Int64,1}:
 39
 35
 29
 29
 31
 87
Related