UNIHIVE

Study Hub UNIPORT ENG 213.1

ENG 213.1 · Computer Programming for Engineers

Arrays

One- and two-dimensional arrays, array operations, and statistics and matrix work on engineering data.

Our notes

1 min read

Declaring arrays

real :: temp(10) ! 10 values, temp(1) to temp(10)
real :: a(3, 3) ! 3 x 3 matrix
integer, parameter :: n = 5
real :: x(n)
Fortran arrays start at index 1 unless you say otherwise: real :: v(0:9).

Filling and using arrays

do i = 1, n
  read *, x(i)
end do
Modern Fortran also allows whole-array operations:
y = 2.0 * x + 1.0 ! every element
total = sum(x)
biggest = maxval(x)
Useful intrinsics: sum, product, maxval, minval, maxloc, size, dot_product, matmul, transpose.

Worked example: mean and standard deviation

Five flow readings (L/s): 2.1, 2.4, 2.2, 2.6, 2.2.
program stats
  implicit none
  real :: q(5), mean, s
  q = (/ 2.1, 2.4, 2.2, 2.6, 2.2 /)
  mean = sum(q) / 5.0
  s = sqrt(sum((q - mean)**2) / 4.0)
  print '(A, F6.3, A, F6.3)', 'Mean = ', mean, ' s = ', s
end program stats
Output: Mean = 2.300 s = 0.200. By hand: deviations −0.2, 0.1, −0.1, 0.3, −0.1; squares add to 0.16; 0.16 / 4 = 0.04; √0.04 = 0.2.

Two-dimensional arrays and matrices

a(i, j) is row i, column j. Fortran stores arrays column by column, so loop over the first index in the inner loop for speed.
c = matmul(a, b) multiplies matrices.

Worked example: matrix product

A = [1 2; 3 4], B = [5 6; 7 8]. C = AB:

  • c(1,1) = 1×5 + 2×7 = 19; c(1,2) = 1×6 + 2×8 = 22
  • c(2,1) = 3×5 + 4×7 = 43; c(2,2) = 3×6 + 4×8 = 50

C = [19 22; 43 50]. matmul(a, b) gives the same.

Engineering uses

Lists of readings, nodal temperatures, stiffness matrices, systems of linear equations (circuit mesh currents, truss forces), time series.

Exams usually ask

  • Declare and fill arrays; find sum, mean, maximum and its position.
  • Write loops to add or multiply matrices.

Common mistake

Reading or writing outside the array (x(6) when x has 5 elements). Fortran does not always stop you; compile with bounds checking (gfortran -fcheck=bounds) while testing.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All ENG 213.1 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.