Struct Julia:更改函数中选择的可变结构属性

Struct Julia:更改函数中选择的可变结构属性,struct,julia,mutable,Struct,Julia,Mutable,我在Julia中创建了一个简单的随机优化函数,并使用可变结构来存储参数值。基本上,我在可变结构中更改了一个参数,通过performance函数传递这些参数,并根据性能更新参数 当我手动指定要更改的参数时,我有一个有效的版本。然而,我想概括一下这一点,这样我就可以选择更改任何给定的参数。例如,将参数的可变结构表示为“args”,而我正在更改参数“P”,我当前代码的关键部分如下所示: args.P = P_new loss_new = performance_function(args) if lo

我在Julia中创建了一个简单的随机优化函数,并使用可变结构来存储参数值。基本上,我在可变结构中更改了一个参数,通过performance函数传递这些参数,并根据性能更新参数

当我手动指定要更改的参数时,我有一个有效的版本。然而,我想概括一下这一点,这样我就可以选择更改任何给定的参数。例如,将参数的可变结构表示为“args”,而我正在更改参数“P”,我当前代码的关键部分如下所示:

args.P = P_new
loss_new = performance_function(args)
if loss_new < loss_old # performance better, keep the new value
    loss_old = loss_new
else # performance worse, go back to old value
    args.P = P_old
end
因此,我可以使用任意参数集,更改参数中的任意参数p,并能够使用任意性能函数。为了说明args是否定义为参数类型

mutable struct Parameter
    a::Float64
    b::Float64
end

args = Parameter(1,2)
然后我想用同样的函数更新a然后b

update_parameter(args,a,performance_function)
update_parameter(args,b,performance_function)

我不知道该怎么做。使用字典有什么聪明的方法吗?还是一种更好的方法来满足我的需求,避免直接操纵可变结构?谢谢

您可以使用
设置字段字段名以
符号给出

julia> mutable struct Parameter
           a::Float64
           b::Float64
       end

julia> function update!(parameters::Parameter, name::Symbol)
           setfield!(parameters, name, 5.0)
           return P
       end
update! (generic function with 1 method)

julia> P = Parameter(1, 2)
Parameter(1.0, 2.0)

julia> update!(P, :a)
Parameter(5.0, 2.0)

julia> update!(P, :b)
Parameter(5.0, 5.0)

但是,如果我正确理解了您的用例,那么字典似乎会更简单,因为如果添加更多参数,您就不必更改
参数的类型定义。

这应该符合我的要求,谢谢。对于一组已定义的参数,我(目前)不需要添加更多参数。只是我有不同的参数集(
Parameter1
Parameter2
say)。然而,看看这将如何与字典一起使用将是很有趣的。
julia> mutable struct Parameter
           a::Float64
           b::Float64
       end

julia> function update!(parameters::Parameter, name::Symbol)
           setfield!(parameters, name, 5.0)
           return P
       end
update! (generic function with 1 method)

julia> P = Parameter(1, 2)
Parameter(1.0, 2.0)

julia> update!(P, :a)
Parameter(5.0, 2.0)

julia> update!(P, :b)
Parameter(5.0, 5.0)