Reputation: 12664
In an answer I wrote previously: https://stackoverflow.com/a/41966459/2749865 I tried to make the code general enough to handle arrays with non-standard indexing. To that end used the construct indices
in place of 1:size(...)
:
[C[i+1, j]/C[i, j]-1 for i in 1:size(C, 1)-1, j in indices(C, 2)]
As you can see, though, I could not figure out how to use indices
when I want to drop the last element.
I can skip the first n
elements by writing drop(indices(C, 1), n)
, but cannot find any way to drop the last n indices.
How can I accomplish this?
Edit: Just to head this one off. In my specific example I could have written
[C[i, j]/C[i-1, j]-1 for i in drop(indices(C, 1), 1), j in indices(C, 2)]
but I'm still interested in hearing if there is a general solution.
Upvotes: 1
Views: 138
Reputation: 12179
Try something like
[C[i+1, j]/C[i, j]-1 for i in indices(C, 1)[1:end-1], j in indices(C, 2)]
In other cases I've used constructs like
inds_interior = map(r->first(r)+1:last(r)-1, indices(A))
to skip the first and last element of each dimension.
Upvotes: 2
Reputation: 18227
If you use Iterators package:
using Iterators
for i in imap(first,partition(indices(C,1),n+1,1))
@show i
end
does the trick. Specifically partition
takes seqeunces of length n+1
and first
takes only the first element, and the last n+1
sequence up to the end of the indices has the first element n
elements before the last.
But perhaps a function would make things look better:
Base.chop(itr,n) = imap(first,partition(itr,n+1,1))
and now:
julia> chop(1:10,3)|>collect
7-element Array{Any,1}:
1
2
3
4
5
6
7
chop
is already defined for strings, removing the last character. It seems the semantics are so close to make overloading it appropriate.
Upvotes: 1