使用此向量的每个元素对向量的每个元素执行计算的简单方法

Ant*_*rev 2 sapply julia

例如,对于向量的每个元素,我想计算残差与该向量的其他元素的总和。这适用于一个元素:

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

但是如果使用 map() 将此函数应用于所有元素,Julia 将返回错误:

map(a, f)
Out: "MethodError: no method matching iterate(::typeof(f))"
Run Code Online (Sandbox Code Playgroud)

在 R 中,使用 sapply() 很容易获得:

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

在 Julia 中是否有同样优雅的方法来做到这一点?

Prz*_*fel 6

只需矢量化f

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