Automatically naming N similar elements in MTK


I’d like a simple way of creating a “vector” of similar elements.

I.e. I’d like:

@named R = [Resistor(R=n) for n in 1:10]

to create a vector of Resistors with resistances 1 to 10. These could be named e.g. R_1R_10

It’s not difficult to achieve this but it’s a hack:

R = [Resistor(name=Symbol(:R_, n), R=n) for n in 1:10]

What do you think?

I think it’s not too difficult to achieve with Julia’s macros.

The hack seems fine. The name field is exposed to take in symbols so that people can programmatically name things. I personally think such a macro extension would be overkill, but no reason to not make one.

There is this syntax for creating several similar components

@named R 1:10 i -> Resistor(R=i)

it’s described in the docstring for @named, which also mentions that it’s not recommended to use it :slight_smile: :man_shrugging:

Didn’t know that…
Seems that creating identical components is fine, though:

julia> @named y[1:3] = foo(x)
3-element Vector{NamedTuple{(:i, :name), Tuple{Int64, Symbol}}}:
 (i = 41, name = :y_1)
 (i = 41, name = :y_2)
 (i = 41, name = :y_3)

But as you say:

    @named y 1:10 i -> foo(x*i)  # This is not recommended

What’s the issue with this form?

Maybe @YingboMa knows

It’s just kind of a hack given how the @named macro is implemented. It’s kind of surprising it works, since it just grabs the args at the highest level and slaps name = $y in there.