Fortran 90 Vector Operations

Implicit Loops

Fortran provides shorthand notation for many simple array operations:

list(1:list_size) = 0.0d0
            

is the same as

do i = 1, list_size
    list(i) = 0.0d0
enddo
            

The list(1:list_size) is an example of an implicit loop for operating on the array. The latter example is an explicit loop. There is no difference in performance between these two Fortran code segments. The compiler will translate both to the same sequence of machine instructions.

Caution

MATLAB has similar notations, but in MATLAB, the implicit loop is many times faster, because MATLAB is an interpreted language. The implicit loop in MATLAB would use a compiled loop, which is roughly equivalent to the loop in Fortran. The explicit loop in MATLAB is interpreted, hence explicit loops should be avoided at all cost in MATLAB.

The general form of an implicit loop of this type is

array(start:end:stride)
            

Examples:

vector(1:vector_length) = vector(1:vector_length) + 4.0d0
            

same as

do i = 1, vector_length
    vector(i) = vector(i) + 4.0d0
enddo
            

Example:

vector1(1:vector_length) = vector2(1:vector_length)
            

same as

do i = 1, vector_length
    vector1(i) = vector2(i)
enddo
            

Example:

vector(1:vector_length:2) = 3.0d0       ! Odd-numbered subscripts
            

same as

do i = 1, vector_length, 2
    vector(i) = 3.0d0
enddo
            

Example:

print *, vector1(1:vector_length)
            

same as

print *, (vector1(i), i=1,5)
            

It is legal, but incompetent to omit the starting and ending subscripts from an implicit loop:

vector1 = vector2 + vector3
            

If you do this, the program will use the minimum and maximum subscripts for the arrays. This is fine if all elements contain useful data. If the array is not fully utilized, however, the loop above will add all the useful elements and all the garbage. For example, if the arrays hold 1,000,000 elements, and the vectors they contain use only 3, then your loop will take about 333,333 times as long as it should.

Where
where (a > 0)
    b = sqrt(a)
elsewhere
    b = 0.0
endwhere
            

Same as

do i = 1, LIST_SIZE
    if ( a(i) > 0 ) then
        b(i) = sqrt(a(i))
    else
        b(i) = 0.0
    endif
enddo