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

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

:+1: Thank you!

view this post on Zulip Notification Bot (Feb 12 2022 at 17:15):

Frank van der Meulen has marked this topic as resolved.


Last updated: Nov 22 2024 at 04:41 UTC