# [ACCEPTED]-Implicit do loop array initialization-fortran

Score: 22

You are initializing an array with `MAXDIM` rows 17 and `NR` columns, and it looks like each column 16 contains the integers 1 to `MAXDIM`.

As a first step, go 15 ahead and write out the actual `DO`-loop:

``````do j=1,NR
do i=1,MAXDIM
myarray(i,j) = i
end do
end do
``````

Collapse 14 the inner loop to an implicit loop structure:

``````do j = 1,NR
myarray(1:MAXDIM,j) = (/ (i, i=1,MAXDIM) /)
end do
``````

When 13 we try to collapse the outer loop, though, something 12 strange happens:

``````myarray = (/ ((/ (i, i=1,MAXDIM) /), j=1,NR) /)
``````

Now, I get an incompatible 11 ranks error as you did. Since I'm not very 10 good at the implicit do-loops either, I 9 looked at the `shape` intrinsic results for the 8 array constructor:

``````print *, shape(myarray)
print *, shape((/ ((/ (i, i=1,MAXDIM) /), j=1,NR) /))
``````

This prints out

``````   5      10
50
``````

The array 7 constructor is simply expanding a 1-D array 6 , flattening any nested array constructions. We 5 can actually drop the second set of `(/ /)` to 4 simplify. Since everything is already in 3 the proper order, we can use the `reshape` intrinsic 2 to ensure proper rank. My full test program 1 is then:

``````program sotest
implicit none

integer, parameter :: MAXDIM = 5
integer, parameter :: NR     = 10

integer :: i
integer :: j
integer :: myarray(MAXDIM, NR)
integer :: myarray_implicit(MAXDIM, NR)

do j = 1,NR
do i = 1,MAXDIM
myarray(i,j) = i
end do
end do

myarray_implicit = reshape((/ ((i,i=1,MAXDIM), j=1,NR) /), (/ MAXDIM, NR /))

print *, all(myarray == myarray_implicit)
end program sotest
``````
Score: 7

The implicit do loop will only create a 6 vector so you'll have to reshape that. Something 5 like this:

``````integer, dimension(m,n) :: myarray
integer :: ix, jx
...
myarray = reshape( [ (ix, ix = 1, m*n) ], [ m, n ] )
``````

or perhaps you want a more complicated, nested, implied-do 4 loop:

``````myarray = reshape( [ ((ix+jx, ix = 1, m), jx = 1, n) ], [ m, n ] )
``````

Note that I'm using the Fortran2003 3 convention of `[ ]` to delimit array constructions, rather 2 than `(/ /)`. Note also that you have to declare 1 the implied do loop index variables.

More Related questions