30
Chapter 8 ARRAYS

Chapter 8

Embed Size (px)

DESCRIPTION

Chapter 8. ARRAYS. Array subscript expressions. Each subscript in an array element designator is an expression of integer type. It need not be a constant. The value of each subscript expression must be within the declared subscript range for the corresponding dimension: - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 8

Chapter 8

ARRAYS

Page 2: Chapter 8

2

Array subscript expressions Each subscript in an array element designator is an expression of

integer type. It need not be a constant. The value of each subscript expression must be within the declared subscript range for the corresponding dimension: Each subscript value must be less than or equal to the upper

bound specified for the corresponding array dimension. Each subscript value must be greater than or equal to the specified

Lower bound; or, if no Lower bound is explicitly specified, it must be greater than or equal to 1 (the default Lower bound).

Example for Array Element Namesinteger, parameter :: EXTENT = 20integer, parameter :: K1 = 1, L3 = 3, M1 = 1, I2 = 2, &J1 = 1, L0 = 0, L16 = 16, I4 = 4, M2 = 2real :: X0real, dimension(EXTENT) :: X1real, dimension(EXTENT, EXTENT) :: X2

Page 3: Chapter 8

3

Array element namesreal, dimension(EXTENT, EXTENT, EXTENT) :: X3

read (unit = *, fmt = *) X1(6)

write (unit = *, fmt = *) X1(I4+2), X1(3*M2)

read (unit =*, fmt = *) X3(L3-1, 2*M1, 13*I2-7)

write (unit =*, fmt = *) X3(2, 2, 19)

read (unit =*, fmt = *) X2(3*J1-1, 3*L0+L16)

write (unit =*, fmt = *) X2(2, 16)

read (unit =*, fmt = *) X1(3)

read (unit =*, fmt = *) X2(K1, L0+2)

X1(1) = X1(3) + L16

X1(I4) = 17.42

X0 = X1(6) + X2(1,2)

write (unit =*, fmt = *) X1(K1), X1(4), X0

Page 4: Chapter 8

4

Vectors, matrices and cubes One-dimensional and two-dimensional arrays may be interpreted in

special ways according to the rules of linear algebra. An array of rank 1 is a vector, an array of rank 2 is a matrix and an array of rank 3 may be viewed as a stack of cubes forming a large block (parallelepiped).

Examples:Examples:

One-dimensional array; vector:

integer, dimension(3) :: A

Two-dimensional array;

integer, dimension(3,3) :: B

A(1) A(2) A(3)

B(1,1) B(1,2) B(1,3)

B(2,1) B(2,2) B(2,3)

B(3,1) B(3,2) B(3,3)

Page 5: Chapter 8

5

Vectors, matrices and cubesThree-dimensional array;

Integer, dimension(3,3,3) :: C

C(1,1,1) C(1,1,2) C(1,1,3)

C(1,2,1) C(1,2,2) C(1,2,3)

C(1,3,1) C(1,3,2) C(1,3,3)

C(2,1,1) C(2,1,2) C(2,1,3)

C(2,2,1) C(2,2,2) C(2,2,3)

C(2,3,1) C(2,3,2) C(2,3,3)

C(3,1,1) C(3,1,2) C(3,1,3)

C(3,2,1) C(3,2,2) C(3,2,3)

C(3,3,1) C(3,3,2) C(3,3,3)

Page 6: Chapter 8

6

Example Declare an array of rank 3 which might me suitable for

representing a hotel with 8 floors and 16 rooms on each floor and two beds in each room. How would the second bed in the 5th room on floor 7 be referenced?

SOLUTIONSOLUTION

Declaration:

INTEGER, DIMENSION(8,16,2) :: Hotel (or any permutation of 8, 16 and 2)

Reference:

Hotel(7,5,2)

Page 7: Chapter 8

7

Whole-array operationsAn array is a variable; thus, the array name (without a subscript)

represents all elements of the array. For instance, an array name in an input or output list causes input or output of all the array elements. There is a rich set of operations on whole arrays; most scalar operations are extended to whole-array operands. A whole-array operation is applied to all elements of the array. A whole-array, denoted by the array name without a subscript, is an array variable. F language permits an array variable in most contexts where a scalar variable is permitted. Assignment is permitted between whole arrays of the same shape:

1) The shape of an array is determined by its rank (number of dimension) and by its extent (number of elements) along each dimension.

2) Two arrays have the same shape if they have the same rank and if their extents agree along each dimension. The subscript ranges (upper and lower subscript bounds) are not required to agree.

Page 8: Chapter 8

8

Whole-array operationsWhole-array assignment

real, dimension(5, 7) :: A, Breal, dimension(0 : 4, 0 : 6) :: Cinteger, dimension(5, 7) :: Iread(unit = *, fmt = *) BC = BI = C ! Elementwise type coercion, with truncation, occurs.A = Iwrite (unit = *, fmt = *) A

Exercise: Study exercises 5.1 (Meissner`s book)

Page 9: Chapter 8

9

Arithmetic and relational operations on whole arraysreal, dimension(5, 7) :: A, B, C

logical, dimension(5, 7) :: T

real, dimension(20) :: V, V_Squared

read (unit = *, fmt = *) B, C, V

A = B + C

T = B > C

C = A * B

V_Squared = V * V

write (unit = *, fmt = *) T, C, V, V_Squared

Page 10: Chapter 8

10

Elemental intrinsic functions Many intrinsic functions (see Appendix A, Meissner`s book), notably

including the mathematical functions, are classified as elemental. An elemental intrinsic function accepts either a scalar or an array as its argument. When the argument is an array, the function performs its operation element wise, applying the scalar operation to every array element and producing a result array of the same shape.

Example:Example:real, dimension(5, 7) :: A, B, Clogical, dimension(5, 7) :: T

...A = max(B,C)T=sin(A) > B

Check elemental intrinsic functions between pages 423-436 (Meissner`s book)

Page 11: Chapter 8

11

Array sections with increment (stride) designator An array section designator may include a third expression, analogous

to the third control parameter of an indexed do construct. This increment (in this context, often called the stride) gives the spacing between those elements of the underlying parent array that are to be selected for the array section:

real, dimension(8) :: A

real, dimension(18) :: V

A = V(1: 15: 2)

By analogy to an indexed do with explicit increment, we see that the values assigned to A are those of V(1), V(3), …, V(15). A negative increment value reverses the normal array element sequence:

A = V(9: 2: -1)

the eight elements are V(9), V(8), V(7),…, V(2)

Page 12: Chapter 8

12

Array sections with increment (stride) designatorreal, dimension (18) :: V

V(2:9)

V(1: 15: 2)

V(2: 17: 5)

Page 13: Chapter 8

13

Array sections with increment (stride) designator real, dimension(5, 7) :: M

M(1: 4, 1: 4)

real, dimension(3, 5) :: E

real, dimension(2, 3) :: F

F = E (1 : 3 : 2, 1 : 5 : 2)

Page 14: Chapter 8

14

Array sections of reduced rank Array section designators may be combined with single subscripts to

designate an array object of lower rank

V( : 5) = M(2, 1: 5)

Here, the elements M(2,1) through M(2,5) form a one-dimensional array section that is assigned to the first five elements of V

Do exercise 5.2.1 on page 231 (Meissener`s book) Read pages between 360 - 368 on Ellis’s book.

Page 15: Chapter 8

15

Intrinsic and array inquiry functions

Intrinsic functions perform many operations that would otherwise have to be programmed with loops. A selection of these functions is listed on pages 233-234 on Meissner’s book.

For exampleFor example:: transpose(matrix) forms the transpose of a matrix (rank-2 array) of any

type.

ubound(array [, dim]) returns the upper bound [in the specified dimension], or a vector of upper bounds.

mask argument in sum, product, any, all, count, maxloc, and minloc is a logical array with the same shape as array, and the function is applied to elements where mask is true.

Page 16: Chapter 8

16

Sum and product (sum & dim) The intrinsic functions sum and product compute the sum or product of

all elements of an array or array section of any numerical type. Sum of selected elements (optional argument mask). mask is an array

of the same shape as the first argument array or it is a scalar, and its type is logical. When mask is present, sum and product operate only on the array elements selected by the mask.

The conditional sum Xi>0.0 xi is denoted by the expression sum (X, mask = (X > 0.0)) The mask locates the positive elements of the vector X. The value of

this expression is 0.7 if X is (0.0, -0.1, 0.2, 0.3, 0.2, -0.1, 0.0). The optional argument dim(dimension) simplifies computation of the

sums or products of all rows or columns of a matrix, or along any one dimension of an array of higher rank. The result array has one less dimension than Matrix; the dimension designated by dim is deleted, or rather it is reduced to a scalar. If the rank of Matrix is 2, sum(Matrix, dim =1) produces a vector containing the column sums, and sum(Matrix, dim=2) produces a vector containing the row sums.

Page 17: Chapter 8

17

Sum and product (sum & dim)Example:Example: Let A be the following 3 by 3 matrix: 1 2 3 4 5 6 2 1 1The function sum with two different dim argument values returns the vector

of column sums (7, 8, 10) and the vector of row sums (6, 15, 4). The sum of products is denoted by the expression sum( product (A, dim = 1) )The argument dim = 1 means that the product is to be computed down

each column of A. The result of product is the vector (8, 10, 18), whose sum is 36.

The product of sums is denoted by the expression product( sum (A, dim =2 ) )The argument dim = 2 means that the sum is to be computed along each

row of A. The result of sum is the vector (6, 15, 4), whose product is 360.

Page 18: Chapter 8

18

STUDY & EXERCISES

Study intrinsic functions any, all, count, maxloc, minloc, maxval and minval on pages 237-241 (Meissner`s book).

Study matmul, transpose, reshape functions on Ellis’s book.

Page 19: Chapter 8

19

The where construct A where construct may be used to assign values to arrays depending

on the value of a logical array expression. where construct has the following form:

where (logical-array-expr) array-var1 = array-expr1

or where (logical-array-expr)

array-var1 = array-expr1...

array-varm = array-exprm

elsewhere

array-varm+1 = array-exprm+1...

array-varn = array-exprn

end where

where each array-varm has the same size as the value of logical-array-expr, in the second form, the elsewhere part is optional.

Page 20: Chapter 8

20

The where construct The logical-array-expr is evaluated element by element, and whenever

the expression is true (false), the value of the corresponding element of each array-expri (in the elsewhere part) is assigned to the corresponding element of array-vari. In the first form, all other elements are left unchanged.

For exampleFor example:: Assume that A and B are declared as integer, dimension(5) :: A = (/ 0, 2, 5, 0, 10 /) real, dimension(5) :: Bthe where construct is where (A > 0) B = 1.0 / real (A) elsewhere B = -1.0 end whereconstruct assigns to B the sequence -1.0, 0.5, 0.2, -1.0, 0.1.

Page 21: Chapter 8

21

Array intrinsics for linear algebra applications The intrinsic functions transpose, dot_product, and matmul

perform essential operations of linear algebra.real, dimension(3, 5) :: Areal, dimension(5, 3) :: B

...

B = transpose(A)dot_product forms the sum of products of corresponding elements

of two vector, which must have the same length.matmul forms the product of a p by r matrix (or a vector of length r)

and an r by s matrix (or a vector of length r); the result is a p by s matrix. The arguments must not both be vectors. For example;

real, dimension(5) :: A, Creal, dimension(5, 3) :: X C = matmul(A, X)

Page 22: Chapter 8

22

Array constructors and array-valued constants An array constructor consists of a List of expressions and

implied do loops, enclosed by the symbols (/ and /): (/ List /)The expressions in the List may be scalar expressions or array

expressions, and all must have the same type and kind. Let`s see the array-valued constants in the following. The first two of the following array constructors form constant vectors of real type, while the third is a constant vector of integer type.

( / 3.2, 4.01, 6.4 /)( / 4.5, 4.5 /)( / 3, 2 /)

The implied do loop form that is permitted in an array constructor is so called because of its resemblance to the control statement of an indexed do construct:

Page 23: Chapter 8

23

Array constructors and array-valued constants (Sublist, Index = Initial value, Limit [ , Increment])The Sublist consists of a sequence of items of any form that is permitted in

the ListThe Index, the Initial value, and the optional Increment are subject to the

same rules that apply to indexed do constructs.Example:Example:(/ (I, I = 1, N) /)(/ ((0.0, J=1, I-1), 1.0, (0.0, J = I+1, N), I = 1, N) /)It must be kept in mind that the rank of an array constructor is always 1.An array constructor always creates an array of rank 1, but the intrinsic

function reshape, which changes the shape of an array, can be applied to an array constructor to create an array of higher rank. The result from reshape is an array whose rank is the number of elements in the shape vector and whose shape is given by the shape vector.

Page 24: Chapter 8

24

Array constructors and array-valued constantsFor example, the following expression constructs an N by N identity matrix:

reshape( ( / ((0.0, J=1, I-1), 1.0, (0.0, J = I+1, N), I = 1, N) / ),( / N, N / )

An array constructor on the right side of an assignment statement (or in the definition of a named constant) must agree in shape with the array on the left.

A(1: 7 : 2) = (/ 11, 6, 14, 5 /)

result is: A(1)=11, A(3)=6, A(5)=14, A(7)=5

Study program F27 on page 254 (Meissner`s book)

Page 25: Chapter 8

25

Array allocation Allocatable arrays and allocated pointer target arrays are deferred-

shape arrays. Allocatable arrays are declared in the usual way, except that the keyword allocatable appears in the list of attributes and that the dimension attribute is only specified. Colons in the array shape specification determine the rank (number of dimension) of the allocatable array, but the Subscript bounds are omitted from the declaration. The Subscript bounds remain to be established at the time the array is actually allocated:

real, dimension( : , : ), allocatable :: Alimonyreal, dimension( : ), allocatable :: Alpenglowreal, dimension( : , : , : ), allocatable :: AlabasterAt various points in the program, allocate statement can then be executed

to create the arrays:allocate(Alimony(5, 1000))allocate(Alpenglow(0 : Range), Alabaster(5, 1000, -17 : -6) )

Page 26: Chapter 8

26

Array allocation Storage space that has been provided for the array can be released by

execution of a deallocate statement:

deallocate(Alimony, Alabaster)

An array that has been deallocated may be reallocated with different Subscript bounds, but the rank cannot be changed.

It is an error to allocate an array that is currently allocated or to deallocate an array that is not currently deallocated. The intrinsic function allocated may be used to determine whether or not an array is currently allocated. At the end of execution of the allocate statement, the designated Integer variable will be set to zero if the allocation is successful and to a positive value otherwise.

Page 27: Chapter 8

27

Exercises do I = 1, 3 do J=1, 3 B(I,J) = I + J end do end doRESULT: 2 3 4 3 4 5 4 5 6 do I =1, 3 do J = 1, 3 if ( I < J) then A(I,J) = -1 else if (I == J) then A(I,J)= 0 else A(I,J) = 1

Page 28: Chapter 8

28

Exercises end if

end do

end do

Read pages between 379 - 401 (Ellis). Do self-test exercises 13.2 on page 402 (Ellis).

Page 29: Chapter 8

29

Examples EXAMPLE 1: EXAMPLE 1: Write an array construct for the 5 element rank 1 array

BOXES containing the values 1, 4, 6, 12, 23.

BOXES = (/1, 4, 6, 12, 23/), or BOXES( : )=(/1, 4, 6, 12, 23/) EXAMPLE 2: EXAMPLE 2: Using the intrinsic subroutine RANDOM_NUMBER, write

a program to simulate the throw of a dice.

PROGRAM throw-diceIMPLICIT NONEINTEGER :: throw, r

CALL RANDOM_NUMBER(r)! R is returned 0 <= r <= 1! NINT(r*5) gives an integer between 0 and 5throw = 1 + NINT(r*5)PRINT*, “die throw = “, throwEND PROGRAM

Page 30: Chapter 8

30

Examples EXAMPLE 3: EXAMPLE 3: MATMUL intrinsic

For the declarations

REAL, DIMENSION(100,100) :: A, B, CWHAT is the difference between C=MATMUL(A,B) and C=A*B ?

C=MATMUL(A,B) performs “proper” mathematical matrix multiplication. Element C(i,j) equals DOT_PRODUCT(A(i, : )

C=A*B, however, performs element-by-element multiplication. Element C(i,j) equals A(i,j)*B(i,j)