Cheeku
Cheeku

Reputation: 873

Fortran array assignment with two indices

I need to initialize a two dimensional array with x*x-y*y, where x and y are indices.

Relevant code is

REAL, DIMENSION(1:XSIZE,1:YSIZE) :: PHI
PHI(1:XSIZE,1:YSIZE) = reshape((/ (i*i,i=1,XSIZE) /),shape(PHI))

But what I really want is something like

PHI(1:XSIZE,1:YSIZE) = reshape((/ (i*i-j*j,i=1,XSIZE,j=1,YSIZE) /),shape(PHI))

But this does not work due to bad syntax.

Upvotes: 0

Views: 254

Answers (1)

IanH
IanH

Reputation: 21461

Initialization in Fortran has a specific meaning - it is the process by which an object acquires a value before the program starts executing. Your examples show assignment, which is one of the many actions that can happen during the execution of a program.

For initialization proper in Fortran 90, you could do something like:

INTEGER :: ix
INTEGER :: iy
REAL, DIMENSION(XSIZE,YSIZE) :: PHI = RESHAPE(  &
    (/ ( (ix * ix - iy * iy, ix = 1, XSIZE), iy = 1, YSIZE) /),  &
    SHAPE=[XSIZE, YSIZE] )

You could also use the initializer (the expression after the =) in the above as the right hand side in an assignment statement.

Other options for execution time assignment of the value include use of do constructs or, with later standards, use of FORALL.

FORALL (INTEGER :: ix = 1:XSIZE, iy = 1:YSIZE) PHI(ix,iy) = ix*ix - iy*iy

Upvotes: 2

Related Questions