Stream: helpdesk (published)

Topic: construct static vector from struct


view this post on Zulip Frank van der Meulen (Feb 12 2022 at 14:56):

I am trying to construct a static vector from a struct. So suppose I have

struct TT
  a
  b
  c
end
t = TT(2, 3, 5)

then I can do this using

using StaticArrays
out = SA[t.a, t.c]

Now I want to write a function that takes t and

ind = [:a, :c]

as input, and returns out. It should be such that it works as well if for example ind=[:b] or ind=[:a, :b]. Any suggestions to this?

view this post on Zulip Mason Protter (Feb 12 2022 at 15:30):

You could do this:

julia> SVector(ntuple(i -> getproperty(t, ind[i]), length(ind)))
2-element SVector{2, Int64} with indices SOneTo(2):
 2
 5

Last updated: Oct 02 2023 at 04:34 UTC