Is there an effective pattern to iterate over the “endpoints” of an array 
along a given dimension?

What I eventually want to accomplish is to apply a function (in this case 
an equality test) to the two end points along a particular dimension of an 
array. I think the pattern is easiest explained by considering 1D, 2D and 
3D:

# assume the existence of some scalar-valued function f(x,y)

A1 = rand(10)
f(A1[1], A1[end]) # d == 1 (the only possible value) -> one evaluation

A2 = rand(10, 15)
map(f, A2[1,:], A2[end,:]) # d == 1 -> 15 evaluations
map(f, A2[:,1], A2[:,end]) # d == 2 -> 10 evaluations

A3 = rand(10, 15, 8)
map(f, A3[1,:,:], A3[end,:,:]) # d == 1 -> 15x8 evaluations
map(f, A3[:,1,:], A3[:,end,:]) # d == 2 -> 10x8 evaluations
map(f, A3[:,:,1], A3[:,:,end]) # d == 3 -> 10x15 evaluations

I just want to consider one dimension at a time, so given A and d, and in 
this specific use case I don’t need to collect the results, so a for-loop 
without an allocated place for the answer instead of a map is just fine 
(probably preferrable, but it’s easier to go in that direction than in the 
other). What I’m struggling with, is how to generally formulate the 
indexing expressions (like [<d-1 instances of :>, 1, <size(A,d)-d instances 
of :>], but not in pseudo-code…). I assume this can be done somehow using 
CartesianIndexes and/or CartesianRanges, but I can’t get my mind around to 
how. Any help is much appreciated.

// T
​

Reply via email to