In Fortran, how do I remove Nth element from an array?

arrays, fortran, intel-fortran, matrix

Solution

Let

a = (/1,3,4,5,7,9,11/)

then

pack(a,mod(a,2)/=0)

will return the odd elements of `a`. This isn't quite the same as removing the 3rd element, but your question suggests that removing the even element(s) is really what you want to do.

If you declare

integer, dimension(:), allocatable :: oddones

then

oddones = pack(a,mod(a,2)/=0)

will leave `oddones` containing the odd elements of `a`. You'll need an up-to-date compiler to use this automatic allocation.

Note that in Fortran, as in any sane language, arrays are of fixed size so removing an element isn't really supported. However, if `a` itself were `allocatable` then you could use `a` on the lhs of the expression. Let's leave it to the philosophers whether or not `a` remains the same under this operation.

Problem

Eg I have array (/1,3,4,5,7,9,11/), how do I remove its 3rd element? I couldn't find an array function which does that, nor I find a loop an elegant solution, since I don't know how to append to an array (this means, add an element next to the previous defined element.) I want to remove all even elements from an array... I know there is only one. I can find its index using MINLOC, but I don't know how to remove an element from array.

Original source