Herman Toothrot
Herman Toothrot

Reputation: 1533

Index multiple non-adjacent elements of a Fortran array

Is there a way in Fortran to access many elements of an array without using a loop?

For example given array of 100 elements

real(100) :: a

can I do something like this to access elements 1,4,7,54,81 that do not follow a regular step?

a(1,4,7,54,81)= 3.21423

Upvotes: 4

Views: 1339

Answers (3)

francescalus
francescalus

Reputation: 32366

As noted before, an array may be used as the indexes of an array. This is a so-called vector subscript.

A([1,4,7,54,81]) = 3.21423

sets the elements given to that value. (This is the same as the earlier answer but using the Fortran 2003+/modern array constructor notation.)

The array can be any rank-1 array, such as a variable or expression:

integer :: idx(5)=[1,4,7,54,81]
A(idx) = 3.21423
A(idx-1+1) = 3.21423

Of course, vector subscripts are of use in other settings, such as referencing:

print *, A(idx)
call sub(A(idx))
A(idx) = A(idx+1) + 5

However, array sections with vector subscripts are subject to various restrictions, such as:

  1. not always may they be arguments to a procedure;
  2. a pointer may not point to them;
  3. not all such sections may be assigned to.

In the third case, if the same index appears more than once in the subscript we can't define it. So

print *, A([1,5,1])

is allowed, but

A([1,5,1]) = 3.

is not.

Upvotes: 3

Holmz
Holmz

Reputation: 724

RESHAPE and WHERE are worth looking at. If you are determining which elements to 'pull out' then maybe ALLOCATE a new variable and stuff the elements of A into B. Maybe something like this:

REAL,    DIMENSION(100)            :: A
LOGICAL, DIMENSION(100)            :: A_Mask
INTEGER                            :: SizeB
REAL,    DIMENSION(:), ALLOCATABLE :: B
!...
A_Mask = .FALSE.
WHERE(A > 1.0)
  A_Mask = .TRUE.
ENDWHERE
SizeB = SUM(A_Mask)
!... then allocate B and fill it.

Upvotes: -2

ewcz
ewcz

Reputation: 13087

you could use a vector subscript: a( (/1,4,7,54,81/) )= 3.21423

Upvotes: 7

Related Questions