Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip every nth element of array

Tags:

arrays

julia

How can I remove every nth element from an array in julia? Let's say I have the following array: a = [1 2 3 4 5 6] and I want b = [1 2 4 5]

In javascript I would do something like:

b = a.filter(e => e % 3);

How can it be done in Julia?

like image 211
Toivo Säwén Avatar asked Apr 29 '26 16:04

Toivo Säwén


2 Answers

Your question title and text ask different questions. The title asks how to skip the Nth element, whereas the Javascript code snippet details how to skip elements based on their value, not their index.

Skipping by Value

We can do this using filter.

filter((x) -> x % 3 != 0, a)

This is basically equivalent to your Javascript code. We can, incidentally, also use broadcasting.

a[a .% 3 .!= 0]

This is more akin to code you would see in array-oriented languages like MATLAB and R.

Skipping by Index

With an extra enumerate call, we can get the indices to operate on.

map((x) -> x[2], Iterators.filter(((x) -> x[1] % 3 != 0), enumerate(a)))

This is roughly what you'd do in Python. enumerate to get the indices, filter to purge, then map to eliminate the now-unnecessary indices.

Or we can, again, use broadcasting.

a[(1:length(a)) .% 3 .!= 0]
like image 71
Silvio Mayolo Avatar answered May 02 '26 07:05

Silvio Mayolo


If you need skipping by index the most elegant way is to use InvertedIndices

julia> using InvertedIndices  # or using DataFrames


julia> a[Not(3:3:end)]
4-element Vector{Int64}:
 1
 2
 4
 5

As you can see all your job here is to provide a range of indices you wish to skip.

like image 41
Przemyslaw Szufel Avatar answered May 02 '26 05:05

Przemyslaw Szufel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!