1次元配列を作る
Fortranの配列添字は標準では1から始まります。宣言時に範囲を指定すれば、0始まりや負の添字も使えます。
配列の合計と平均FORTRAN
program array_basic
implicit none
real :: scores(1:4) = [70.0, 80.0, 90.0, 100.0]
real :: average
average = sum(scores) / real(size(scores))
print *, 'sum =', sum(scores)
print *, 'average =', average
end program array_basic実行結果OUTPUT
sum = 340.000000
average = 85.0000000配列の範囲と組み込み関数
scores(2:4)のように一部を取り出せます。minval、maxval、count、any、allを組み合わせると集計を短く書けます。
合格者数を数えるFORTRAN
program count_pass
implicit none
integer :: scores(5) = [55, 72, 80, 49, 91]
print *, count(scores >= 60)
print *, maxval(scores), minval(scores)
print *, scores(2:4)
end program count_pass実行結果OUTPUT
3
91 49
72 80 49配列全体を扱う式は読みやすい一方、どの要素が変更されるかを確認する必要があります。計算前後の配列をprint *で一時的に表示するとデバッグしやすくなります。
2次元配列で表を扱う
2次元配列は行, 列の順で要素を指定します。sum(matrix, dim=1)なら列ごと、dim=2なら行ごとに集計できます。
行列の合計FORTRAN
program matrix_sum
implicit none
integer :: matrix(2, 3)
matrix = reshape([1, 2, 3, 4, 5, 6], [2, 3])
print *, 'all =', sum(matrix)
print *, 'columns =', sum(matrix, dim=1)
print *, 'rows =', sum(matrix, dim=2)
end program matrix_sum実行結果OUTPUT
all = 21
columns = 3 7 11
rows = 9 12reshapeの値はFortranの配列の並び方に従って格納されます。外部データと連携するときは、行と列の順序を実際の入力形式と照合してください。
練習
5人分の点数配列を作り、平均以上の点数だけを別の配列へ入れる処理を書いてください。まずループで実装し、次にpack(scores, scores >= average)を使う方法と比べてみましょう。