Fortran 90: Array Operations

Let's start with a simple example. Suppose we wish to add two arrays A and B and put the result in C. In Fortran 77 , we would have something like
do i=1,n
do j=1,n
C(j,i) = A(j,i) + B(j,i)
In Fortran 90, it is as simple as C = A + B .

Most of the intrinsic functions operate component-wise on arrays. C = sin(A) is equivalent to (in this case, A is a one dimensional array)

do i=1,n
C(i) = sin(A(i))

Note: C = A*B multplies corresponding elements in A and B. It does NOT do matrix multiplication. There are some intrinic functions for matrix multiplication (matmul) and dot products (dot_product). The matrix multiply would look like C = matmul(A,B) . There are a number of other intrinic subroutines and functions for finding the size and rank of an array, reshaping an array, converting an array to vector and back, tranposes, and many more.

Array sections

Along with the ability to operate on whole arrays comes the ability to operate on just part of an array. The following examples show operation on the rows, columns, or a sub-matrix of a matrix.
real*8 :: A(3,3)
real*8 :: B(2,2)
real*8 :: v(3)

 v(:) = A(:,1)   ! set v equal to the first column of A 
 v(:) = A(1,:)   ! set v equal to the first row of A
 B(:,:) = A(1:2,1:2) ! B is the upper 2x2 part of A
In general, a section of an array is specified by v(start:end:stride) A bare colon (:) specifies the entire dimension, as shown in the examples above.

Obtaining the diagonal of a matrix requires converting the matrix to an array, and then using a stride that is one greater than the dimension.

Return to Fortran 90 index