4

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
0

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

print *, A([1,5,1]) is not working for me, I get "Error: Fortran 2003: [...] style array constructors at (1)"
If you are stuck with using Fortran 90/95 code, then use (/1,5,1/) rather than [1,5,1].
-2

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.

2 Comments

The argument to SUM must be of numeric type. The language has an intrinsic to COUNT true values in a logical array expression. I don't think the code in this answer addresses the question in any useful way.
Not only is this answer way off beam, it also looks as if its author is suggesting a home-brewed alternative to the pack function !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.