Skip to main content

Array and Matrix

src/05_array.f90
! Program : Array

PROGRAM array
IMPLICIT NONE

INTEGER :: vec(10)
INTEGER :: ii

OUTER_LOOP : DO ii = 1, 10
vec(ii) = ii
ENDDO OUTER_LOOP

DO ii = 1, 10
PRINT '(i2)', vec(ii)
ENDDO

END PROGRAM array

There is intrinsic SIZE function to determine the length of a vector, SIZE(vec). Another example where we use implied DO loop to assign an array:

src/05_array2.f90
PROGRAM array2
IMPLICIT NONE

INTEGER, DIMENSION(10) :: vec
INTEGER :: ii

vec = [(ii, ii = 1, 10)]

DO ii = 1, SIZE(vec)
PRINT '(i2)', vec(ii)
ENDDO

END PROGRAM array2

Dynamic array allocation with ALLOCATABLE:

INTEGER, DIMENSION(:), ALLOCATABLE :: a
INTEGER i
a = [(i, i = 1, 10)]
DEALLOCATE(a)

See dynamic array allocation in this example.

Assign high dimensional array with RESHAPE:

a = RESHAPE([1, 2, 3, 4, 5, 6], [2, 3])
! will produce
! 1 3 5
! 2 4 6

a = RESHAPE([1, 2, 3, 4, 5, 6], [2, 3], order=[2, 1])
! will produce
! 1 2 3
! 4 5 6

Matrix multiplication:

src/05_matrix_mult.f90
! Program : Matrix multiplication

PROGRAM matrix_mult
IMPLICIT NONE

INTEGER, DIMENSION(2, 3) :: A = RESHAPE([1, 2, 3, &
4, 5, 6], &
shape(A), &
order=[2, 1])

INTEGER, DIMENSION(3, 2) :: B = RESHAPE([1, 2, &
3, 4, &
5, 6], &
shape(B), &
order=[2, 1])

INTEGER, DIMENSION(2, 2) :: output
INTEGER :: ii

output = MATMUL(A, B)

DO ii = 1, 2
PRINT *, output(ii, :)
END DO
END PROGRAM matrix_mult

You can assign all the array element same value by assigning it a scaler value:

INTEGER, DIMENSION(2, 2) :: a
a = 1
! will produce
! 1 1
! 1 1