如何在朱莉娅中具有变量的函数



如果您不介意,请帮助我,我该如何具有x的函数如下:

此功能计算x

的两个值
function MOP2(x)
    n=length(x);
    z1=1-exp(sum((x-1/sqrt(n)).^2));
    z2=1-exp(sum((x+1/sqrt(n)).^2));
    z=[z1;z2];
    return z
end

在主代码中,我想拥有

costfunc=F(x)

,但我不知道它是否存在于朱莉娅。在MATLAB中,我们可以如下

costfunc=@(x)  MOP2(x)

Julia中是否有@这样的功能?

非常感谢。

是的,有一个语法。

这些称为匿名函数(尽管您可以为它们分配名称(。

这里有几种方法。

x -> x^2 + 3x + 9
x -> MOP2(x) # this actually is redundant. Please see the note below
# you can assign anonymous functions a name
costFunc = x -> MOP2(x)

# for multiple arguments
(x, y) -> MOP2(x) + y^2
# for no argument
() -> 99.9
# another syntax
function (x)
    MOP2(x)
end

这是一些用法示例。

julia> map(x -> x^2 + 3x + 1, [1, 4, 7, 4])
4-element Array{Int64,1}:
  5
 29
 71
 29

julia> map(function (x) x^2 + 3x + 1 end, [1, 4, 7, 4]) 
4-element Array{Int64,1}:
  5
 29
 71
 29

请注意,您不需要创建像x -> MOP2(x)这样的匿名函数。如果功能采用另一个功能,则可以简单地传递MOP2而不是传递x -> MOP2(x)。这是round

的示例
julia> A = rand(5, 5);
julia> map(x -> round(x), A)
5×5 Array{Float64,2}:
 0.0  1.0  1.0  0.0  0.0
 0.0  1.0  0.0  0.0  1.0
 0.0  0.0  1.0  0.0  1.0
 1.0  1.0  1.0  1.0  0.0
 0.0  0.0  1.0  1.0  1.0
julia> map(round, rand(5, 5))
5×5 Array{Float64,2}:
 0.0  1.0  1.0  0.0  0.0
 0.0  1.0  0.0  0.0  1.0
 0.0  0.0  1.0  0.0  1.0
 1.0  1.0  1.0  1.0  0.0
 0.0  0.0  1.0  1.0  1.0

传递函数作为参数时,还有do语法。

如果您想为匿名函数命名,则可以定义其他功能,例如

costFunc(x) = MOP2(x) + sum(x.^2) + 4

并稍后使用costFunc

如果要调用其他名称的函数,则可以写

costFunc = MOP2

如果它在函数内。否则。在全球范围中,最好在分配语句之前添加const

const constFunc = MOP2

这对于类型稳定性原因很重要。

最新更新