Suppose I wish to take as input some integer d
and iterate over all tuples (i_1, ... i_d)
, with each entry lying in 1 to 10. For example, I may take as input a vector v
of length d
and compute the sum v_1 i_1 + ... + v_d i_d
for every such tuple of dimension d
. How can I achieve this ? CartesianIndices does not seem to solve this.
Maybe I don’t understand the question, but some variant of
d = 2
[sum(Tuple(ι)) for ι in CartesianIndices(ntuple(_ -> 1:10, d))]
should work (make d
a Val
type for type stability and/or wrap in a vec
or flatten if needed, etc).
2 Likes
I’m not certain what you are trying to do, but see if this Iteration utilities · The Julia Language is useful.
Thanks ! CartesianIndices(ntuple(_ -> 1:10, d))
seems like a great way to generate the indices. I
seems to be a collection through which I can iterate, and each iteration is of type CartesianIndex{d}
.
- Is it possible to convert an object of type
CartesianIndex{d}
into a vector. You showed how to convert it into aTuple
? - If not, can we take a linear combinations, such as
v_1 i_1 + ... + v_d i_d
?
Yes, eg
ι = CartesianIndex(1, 2, 3)
collect(Tuple(ι))
but I would recommend SVector(Tuple(ι)...)
for efficiency.
1 Like
SVector(Tuple(I))
works.
2 Likes
Thank you, it worked !
Thank you, it worked !