Complete Fortran Lecture Notes
Complete Fortran Lecture Notes
eoasare
September, 2016
Email : fortranclass@gmail.com
Program Structure
Variables and Statements
Data types and Numerical Operators
Character Processing
Unformatted and formatted output
Course Content
Part3 : Fortran 90 Array
Functions
Subroutine
Module
Recommended Textbooks
1 Fortran 90/95 for Scientists and Engineers
by: Stephen J. Chapman
3 Fortran 90 Handbook
by: Jeanne C. Adams, Walter S. Brainerd, Jeanne T. Martin, Brian
T. Smith, Jerrold L. Wagener
Lectures
Grading
1 Files are organized into directories, or listings of files. Like all other
files in Linux, a directory is also treated as a file. Each directory can,
in turn, contain subdirectories, creating hierarchical listings.
5 Blank space are allowed but it is very difficult use those files
<filenamebody>.< extension>
where the extension (usually no more than three or four letters) indicates
the file type. For example
.txt : text file
.html (or .htm) : INTERNET page file
.tex : document in the TeX (or LaTeX)
.ps : postscript file
Meaning of some commands
1 ’mkdir’ for creating a directory folder
eg. mkdir dirname this creates directory called dirname
2 ’cp’ for copy file or directory to another file for directory
eg. cp filename1 filename2 both files will be in the directory
for directory cp -r dirname1 dirname2
You can copy files/directories into a different directory
C-r - search backward (searching towards the top of the current buffer)
C-s - search forward (searching towards the end of the current buffer)
M-% - replace forward
C-SPC - mark the beginning of the text for copying/moving/deleting
C-w - cut the text from buffer to the clipboard
C-y - paste the text from the clipboard at the position of the cursor
C- - undo the last change
ESC ESC ESC - cancel the last operation
Saving Document
After executing C-x C-s command, the minibuffer at the bottom of your
screen ask for the file name, type the name and the extension. To replace
an existing file, press the TAB key during writing the file name and
Emacs automatically adds the rest of the name.
Course Objective
The first part will involve the students learning the basic principles
of Fortran programming
To be able to understand the basics of any Fortran code
Students will learn how to write their own simple programs
Learn how to manipulate data input/output files
To use Fortran to solve climate/meterology related problems.
Good News
No previous programming experience is required.
What is computer program?
Versions/Standards
Fortran 66 - first standard
Fortran 77 - character handling
Fortran 90 - array and modular programming
Fortran 95 - functional programming
Fortran 2003 - object-oriented and generic programming
Fortran 2008 - concurrent programming.
Fortran 2015 - is under development
Fortran Program Structure without subprograms
[Declaration statements]
name (program name) must:
[Execution statements]
Begin with a letter
END [ PROGRAM name] (upper/lower case)
It contains letters, digits 0-9,
and underscore characters
Maximum of 31 characters.
names are case-insensitive.
Fortran Program Structure with internal subprograms
Subprogram(s)/procedures can
[PROGRAM name ] appears after the end of the main
program.
[IMPLICIT NONE]
Subprograms that are not contained
[Declaration statements] in the main program are called
external subprograms/procedures.
[Execution statements]
IMPLICIT NONE
When this statement is used in the program, any variable that does
not appear in an explicit type declaration statement is considered
error.
The decimal form consist of string of digits with exactly one decimal
point. e.g 1.4, -13.5, +0.04, 33333.5
Variables
Declaration of Variables
Variables Attributes
Various Fortran attributes may be specified for variables in their
type-declaration statement.
The PARAMETER attribute dictates that a constant is being
defined. A variable declared with this attribute may not have its
value changed within the program unit.
The PARAMETER attribute is used after the data type keyword,
followed by variable name followed by an = and then value for the
variable.
EXAMPLE :
REAL, PARAMETER :: PI = 3.143
! PI will be equal to 3.14 throughout the program
INTEGER, PARAMETER :: TOTAL = 10
! TOTAL will be equal to 10 throughout the program
Features of Fortran Program 10/14
Variable Initialization
Program Comments
Arithmetic Operator
variable = expression
where variable has been declared and therefore has a type
If the type of variable and expression are identical, the result is
saved to variable.
If the type of variable and expression are not identical, the result of
expression is converted to the type of variable.
1 INTEGER = REAL
The RHS is evaluated and then the value is truncated (all the
decimal places lopped off ) then assigned to the LHS.
2 REAL = INTEGER
The INTEGER is evaluated as REAL. The RHS expression is simply
stored (approximately) in the LHS.
Mixed Type Assignment - example 7/13
Relational Operator
Operator Meaning
< or .LT. Less than
> or .GT. Greater than
== or .EQ. Identically equal to
/ = or .NE. Not equal to
<= or .LE. Less than or equal to
>= or .GE. Greater than or equal to
Operators in Fortran 9/13
Logical Operator
Character Operator
Example:
’Man’ // ’chester’ gives ’Manchester’
CHARACTER(LEN = 7) :: word 1 =“missing”
CHARACTER(LEN = 3) :: word 2 = “you”
CHARACTER(LEN = 10) :: ans
ans = word 1 // word 2 ! missingyou
Operators in Fortran 11/13
Character substrings
Function Meaning
INT(x) Truncate a real number to an integer
NINT(x) Round a real number to the nearest integer
REAL(x) Convert to real
CEILING(x) Nearest integer greater than or equal to x
FLOOR(x) Nearest integer less than or equal to x
CMPLX(x) Real to complex
FRACTION(x) Fractional part of real
Write and Run fortran program 1/3
Deterministic DO loops
The number of times the section is repeated is stated explicitly.
Non-deterministic DO loops
The number of repetitions is not stated in advance.
Fortran 90 Control Structures 2/10
If step is positive
The control-var receives the value of initial
If step is negative
The control-var receives the value of initial
Count down loop always requires a step. That is the loop will not
work without a specified step
Deterministic Do loop Example 5/10
What do we need ?
If construct
Deterministic Do loop
Dimension attribute
PROGRAM func x0
! this program solve a function with 11 data point
IMPLICIT NONE
INTEGER, PARAMETER :: i start = 0, i end = 10
INTEGER :: icount
REAL, DIMENSION (i start : i end) :: f xy !array declaration
DO icount = i start, i end !do loop with step =1
IF ( icount < 4 ) THEN !1st condition
f xy (icount) = 0
ELSE IF ( icount >= 4 .AND. icount <= 5) THEN !2nd condition
f xy ( icount ) = 0.1 * (icount - 4)
ELSE IF ( icount >= 5 .AND. icount <= 6 ) THEN !3rd condition
f xy( icount ) = 20 - 0.1 * ( icount - 4 )
ELSE !last condition
f xy ( icount ) = 0
END IF
PRINT*, icount, f xy ( icount )
END DO
END PROGRAM func x0
Fortran 90 Control Structures 6/10
DO
< statement body >
IF (< logical-expression > ) EXIT
< statement body >
END DO
DO
< statement body >
IF (< logical-expression > ) CYCLE
< statement body >
END DO
X (−1)n ∞
pi 1 1 1 1
= 1 − + − + − ...
4 3 5 7 9 2n + 1
n=0
Integer values are right justified in their fields. This means that integers
are printed out so that the last digit of the integer occupies the
rightmost column of the field.
The I descriptor has the general form
rIw or rIw.m
where r, w, and m have the meanings given in the above table.
Example
INTEGER :: x = 12345
PRINT’(I5)’, x !integer with field width = 5, 12345 is the output
If the integer is too large to fit into the field in which it is to be printed,
then the field is filled with asterisk.
PRINT’(I3)’, x !integer with field width = 3, **** is the output
Formatted Output 3/7
Real data can be printed in exponential form using the E descriptor. Real
values displayed by E descriptor are normalized to a range between 0.1
and 1.0. For example 4.096 x 103 will appears as 0.4096E+04 using the
E descriptor
The E descriptor has the general form
rEw.d
The width w of E descriptor must satisfied the expression
w ≥ d +6 where d has the same meaning given in the table
Example:
REAL :: res = 23456
PRINT’(E11.5)’, res !output = 0.23456E+05
PRINT’(E13.5)’, res !output = 0.23456E+05, check the position
PRINT’(E8.2)’, res !output = 0.23E+05
Formatted Output 5/7
The X Descriptor is used to add one or more blanks space between two
values on the output line.
The X Descriptor has the form of a positive integer followed by X:
nX
where n is the number of blanks to insert.
Example:
CHARACTER(LEN = 7) :: dept = ’physics’
REAL :: ans = 2345.6
PRINT’(ES8.2,A7)’, ans, dept ! output = 2.35E+03physics
PRINT’(ES8.2,2X,A7)’, ans, dept ! output = 2.35E+03 physics
where 2X create two blank spaces between ES8.2 and A7 outputs
What is computer program?
Versions/Standards
Fortran 66 - first standard
Fortran 77 - character handling
Fortran 90 - array and modular programming
Fortran 95 - functional programming
Fortran 2003 - object-oriented and generic programming
Fortran 2008 - concurrent programming.
Fortran 2015 - is under development
Fortran Program Structure without subprograms
[Declaration statements]
name (program name) must:
[Execution statements]
Begin with a letter
END [ PROGRAM name] (upper/lower case)
It contains letters, digits 0-9,
and underscore characters
Maximum of 31 characters.
names are case-insensitive.
Fortran Program Structure with internal subprograms
Subprogram(s)/procedures can
[PROGRAM name ] appears after the end of the main
program.
[IMPLICIT NONE]
Subprograms that are not contained
[Declaration statements] in the main program are called
external subprograms/procedures.
[Execution statements]
IMPLICIT NONE
When this statement is used in the program, any variable that does
not appear in an explicit type declaration statement is considered
error.
The decimal form consist of string of digits with exactly one decimal
point. e.g 1.4, -13.5, +0.04, 33333.5
Variables
Declaration of Variables
Variables Attributes
Various Fortran attributes may be specified for variables in their
type-declaration statement.
The PARAMETER attribute dictates that a constant is being
defined. A variable declared with this attribute may not have its
value changed within the program unit.
The PARAMETER attribute is used after the data type keyword,
followed by variable name followed by an = and then value for the
variable.
EXAMPLE :
REAL, PARAMETER :: PI = 3.143
! PI will be equal to 3.14 throughout the program
INTEGER, PARAMETER :: TOTAL = 10
! TOTAL will be equal to 10 throughout the program
Features of Fortran Program 10/14
Variable Initialization
Program Comments
Arithmetic Operator
variable = expression
where variable has been declared and therefore has a type
If the type of variable and expression are identical, the result is
saved to variable.
If the type of variable and expression are not identical, the result of
expression is converted to the type of variable.
1 INTEGER = REAL
The RHS is evaluated and then the value is truncated (all the
decimal places lopped off ) then assigned to the LHS.
2 REAL = INTEGER
The INTEGER is evaluated as REAL. The RHS expression is simply
stored (approximately) in the LHS.
Mixed Type Assignment - example 7/13
Relational Operator
Operator Meaning
< or .LT. Less than
> or .GT. Greater than
== or .EQ. Identically equal to
/ = or .NE. Not equal to
<= or .LE. Less than or equal to
>= or .GE. Greater than or equal to
Operators in Fortran 9/13
Logical Operator
Character Operator
Example:
’Man’ // ’chester’ gives ’Manchester’
CHARACTER(LEN = 7) :: word 1 =“missing”
CHARACTER(LEN = 3) :: word 2 = “you”
CHARACTER(LEN = 10) :: ans
ans = word 1 // word 2 ! missingyou
Operators in Fortran 11/13
Character substrings
Function Meaning
INT(x) Truncate a real number to an integer
NINT(x) Round a real number to the nearest integer
REAL(x) Convert to real
CEILING(x) Nearest integer greater than or equal to x
FLOOR(x) Nearest integer less than or equal to x
CMPLX(x) Real to complex
FRACTION(x) Fractional part of real
Write and Run fortran program 1/3
Nested DO Loops
If one loop is completely inside another one, the two loops are called
nested loops.
For each control-var of the outer loop, the entire inner loop has to be
completed before next iteration in the outer loop.
When Fortran compiler encounters an END DO statement, it associates
that with the innermost currently open loop.
Therefore, the first END DO statement closes the inner loop and the last
the outermost loop.
Fortran 90 Control Structures 2/8
PROGRAM nested
IMPLICIT NONE
INTEGER :: icount, jcount ! counters declaration
DO icount = 1, 3, 1 !the outer loop statement
DO jcount = 1, 5, 1 !inner loop statement
PRINT*, icount, ” * ”, jcount, ” = ”, icount * jcount
END DO !end do for inner loop
END DO !end do for outer loop
END PROGRAM nested
for each icount step, jcount will run from 1 to 5 before icount will
update.
for the outer loop, the inner loop serve as the executable statement.
for the inner loop, PRINT statement is the executable statement.
Fortran 90 Control Structures 2/8
DO WHILE construct
The DO WHILE loop always exits at the top of the loop construct as
this is where the test takes place.
The syntax is as follows:
The body statements in the DO WHILE block are executed for as long as
the result of the logical-expression remains TRUE.
The DO range is executed repeatedly as follows.
Prior to each execution of the DO range, the logical expression is
evaluated. If it is true, the range is executed; if it is false, the DO
WHILE construct terminates.
DO WHILE - example 4/8
PROGRAM do while eg
IMPLICIT NONE
INTEGER :: i
REAL :: sum
i=0 ! i initialization
sum = 0.0 ! sum initialization
DO WHILE ( i < 5 ) ! condition for the loop
i = i +1 ! i counter increment
sum = sum + i ! summing over i
PRINT 20, i, sum ! print each step
END DO
PRINT 20, i, sum ! print only final step
20 FORMAT (I2, 2x, F5.2) ! print format
END PROGRAM do while eg
Fortran 90 Control Structures 5/8
Programs seldoms run corrrectly the first time, even for experienced
programmers. Errors in programs are known as bugs, the process of
locating and eliminating them is known as debugging.
Four types of errors are found in Fortran programs:
Compilation errors
Run-time errors
Logical errors
Rounding errors
Debugging Fortran Programs 2
Compilation Error
Compilation errors are errors in syntax and construction, like spelling
mistakes or wrong punctuation that are picked up by the compiler during
compilation, the process whereby your program is translated into
machine code. They are the most frequent type of error. The compiler
prints a messages, which may or may not be helpful, when it encounters
such an error.
Run-time Error
If a program compiles successfully, it will run. Errors occuring at this
stage are called run-time errors, and are invariably fatal, i.e. the program
“crashes” or abort during execution. A run-time error occurs when an
illegal mathematical operation is attempted during program execution
(for example attempting to divide by 0).
Debugging Fortran Programs 3
Logical Error
These are errors in the actual algorithm you are using to solve a problem,
and are the most difficult to find; the program runs, but gives the wrong
answer! It’s even worse if you don’t realize the answers are wrong.
Rounding Error
At times a program will give numerical answers to a problem which
appear inexplicably different from what we know to be the correct
mathematical solution. This can be due to rounding error which results
from the finite precision available on the computer
Assignment
Write a fortran program to evaluate exponential function using DO
WHILE construct
∞
x
X xn x2 x3
e = =1+x + + + ...... for all x
n! 2! 3!
n=0
Write a program which will assigned in two real numbers x and y and will
print out the product z.
Steps
Write the formula for the product and assign the results to the 3
variable
Write a program which will read in the radius of cycle and the program will
compute the area and the perimeter
Step
Declare 3 variables for the - radius, area and perimeter
Declare pi using the parameter attribute hope you remember?
Use PRINT statement to prompt the user to enter the value for the radius,
e.g - PRINT*, ’enter the value of the radius of the cycle’
Use READ statement to assign the radius
Assign the value of the area using the formula π × radius 2
Remember how to write pi and exponentiation in fortran
Please each group should submit their program file to the email below
Subject of the mail - Assignment 1
Body of the mail - group members name and their index numbers
Email : fortranclass@gmail.com
eoasare
January, 2017
Email : fortranclass@gmail.com
Function
Subroutine
Module
Open/close statements
Read and write Statements
Read data with/without header
Reading table as array
Formatted and unformatted files
3 Fortran 90 Handbook
by: Jeanne C. Adams, Walter S. Brainerd, Jeanne T. Martin,
Brian T. Smith, Jerrold L. Wagener
know how to read external dataset and write your your output
into external files
Function Statement 1
Functions syntax 2
Function receives inputs from the outside world via its dummy
arguments, does some computations, and returns the result
with the function-name
The function-name must appear in one or more assignment
statement like this:
function-name = expression
where the result of expression is saved to the name of the
function
Note that function-name cannot appear in the right-hand
side of any expression except recursive function.
The variables listed in the argument list in the function
definition are called dummy variables. Their names do not
have to match the names used in parts of the program where
the function is called.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions
Function Statement
Note that a function without dummy arguments is declared with
empty parentheses ( ). The syntax is as:
type FUNCTION function-name ( )
IMPLICIT NONE
[ declaration part ]
[ execution part ]
END FUNCTION function-name
If the function is written in the same file as the main program,
it must appear after the end of the main program.
The arguments used when the function is actually invoked are
called actual arguments. They may be variables (e.g. x, y),
constants (e.g. 1.0, 2.0) or expressions (e.g. 3.0 + x, 2.0/y ),
but they must be of the same type, number and at the same
positions as the dummy arguments.
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions
a+b+c
s=
2
The area of a triangle can also be calculated from its
semiperimeter and side lengths using Heron’s formula
p
area = s(s − a)(s − b)(s − c)
The area is coded as function
see next page for the program
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Functions - external function example
PROGRAM func eg
! compute area of triangle using Heron’s Formula
IMPLICIT NONE
REAL, EXTERNAL :: tri area ! declare external function
REAL :: side1,side2,side3,ans
PRINT*,’Enter the sides of the triangle’
READ*, side1, side2, side3 ! input triangle sides
ans = tri area(side1,side2,side3) ! calculate area using function
PRINT’(A, F6.3)’,’Area of triangle is = ’, ans
END PROGRAM func eg
Recursive Functions
Write a program that will read in the lengths a and b of two sides
of a triangle and the angle between them θ (in degrees). Calculate
the length of the third side c using the cosine rule:
The program should print out the type of triangle based on the
sides
c 2 = a2 + b 2 − 2abcos(θ)
Write the cosine rule as a function
Outline
Variables to be declared
Declare function
lengths and angle should be read from the keyboard
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine
Subroutine syntax
To call Subroutine
IMPLICIT NONE
INTEGER, PARAMETER :: point=5
REAL, DIMENSION (point) :: xobs,xmod
REAL :: ans
PRINT*, ’enter the values for the observed data’ !enter the values for the
observed data
READ*, xobs
PRINT*,’enter the values for the model dats’ !enter the values for the model data
READ*, xmod
CALL my rmse(xobs, xmod, ans) !subroutine call
END DO
rmse=SQRT(sum val/point) !rmse complete formula
PROGRAM cosinerule
!This formula computes area of triangle using cosine rule
IMPLICIT NONE
REAL :: side1, side2, angle 1 ! input data declaration
REAL :: side3 ! output data declaration
PRINT* , ’Enter the two sides of the triangle’
READ* , side1, side2
PRINT* , ’Enter the angle between the sides’
READ* , angle 1 ! enter angle in degrees
CALL triangle side( side1, side2, angle 1, side3 ) ! subroutine call
PRINT 10, ’the third side of the triangle = ’, side3
10 FORMAT ( A, 2x, F5.3 ) ! print format
END PROGRAM cosinerule
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Subroutine - external Subroutine example - continue
PROGRAM cosinerule
!This formula computes area of triangle using cosine rule
IMPLICIT NONE
Recursive Subroutine
Fortran 90 MODULE
Module Syntax
PROGRAM stats
USE stat eg !use the module name
IMPLICIT NONE
REAL, DIMENSION(10) :: mydata !actual input data name
REAL :: mymean, mystd dev !mean and standard deviation
INTEGER :: n # of input data
PRINT*, ’enter the number of data point and data value’
READ* , n, mydata
mymean = mean(mydata, n) !mean function
mystd dev = std dev(mydata, n, mymean) !standard deviation
function
!mystd dev = std dev(mydata, n, mean(mydata, n))
!alternative to use mean function
PRINT 10, ’ mean is: ’, mymean, ’standard deviation is:’, mystd dev
10 FORMAT (A, 2X, F4.2, 2X, A, 2X, F4.2)
END PROGRAM stats
Programming with Fortran II (MET 254) eoasare
Fortran Subprogram
Fortran 90 Modules - example
PROGRAMMING WITH
FORTRAN II
Email:fortranclass@gmail.com
FORTRAN ARRAY
- terminology and referencing
- Array declaration and syntax
- Array construction and expression
- Dynamical Allocation of array
READ and WRITE data from/to file
- Open statement
- Attributes of open statement
- Read and write Statement
- Read data with/without header
- Reading table as array
- Formatted and unformatted files
Practical session using meteorological data
- Manipulate field data
- Brief introduction to gnuplot
Programming with Fortran II
Fortran Array
Terminology
Individual elements
Individual elements and sections of an array are uniquely identified
through sub- scripts, one per rank separated by commas. This
subscript is an integer value (or an expression whose result is an
integer value)
REAL, DIMENSION(8) :: a
INTEGER, DIMENSION(5,4) :: b
a(5) !fifth element
b(4,2) !element at intersection of the 4th row and 2nd column.
Programming with Fortran II
Fortran Array
Array Section
Printing Arrays
Input of Arrays
Most intrinsic functions that we use for scalars, for example SIN,
INT, and ABS, are elemental; i.e. they can also apply to arrays.
For example:
REAL :: A= (/ 0.2, 0.3, 0.4, 0.5, 0.6 /)
PRINT *, SIN(A)
gives
0.1986693 0.2955202 0.3894183 0.4794255 0.5646425
There are, in addition to the elemental functions, intrinsic
functions whose arguments are specifically arrays.
Some of them are listed in the next slide
Programming with Fortran II
Fortran Array
Intrinsic Functions for Arrays
Function Description
MAXVAL(A) Gives the maximum value of array A
MINVAL(A) Gives the minimum value of array A
MAXLOC(A) Index location of maximum value of A
MINLOC(A) Index location of minimum value of A
PRODUCT(A) Gives product of the values in array A
SIZE(A) Gives the number of values of array A
MATMUL(A,B) Gives the cross product of arrays A and B
TRANSPOSE(A) Gives the transpose of array A
SUM(A) Gives the sum of the values in array A
REAL, DIMENSION(-10:10,23,14:28) :: A
4. SIZE(array name [,DIM])
Returns a scalar containing the total number of array elements
either in the whole array or in an optionally specified dimension.
For example,
PRINT*,SIZE(A) ! produces 7245 ie multiplication of dimension
PRINT*,Size(A,1) ! produces 21 ie element in first dimension
PRINT*,Size(4) ! is an error as the argument must not be scalar
Programming with Fortran II
Fortran Array
Array constructors
Array constructors
Array constructors
PROGRAM array
IMPLICIT NONE
INTEGER, DIMENSION (5) :: myvec = (/23,21,100,1,5/)
REAL, DIMENSION (4), PARAMETER ::mycon=(/0.1,0.2,0.3,0.4/)
REAL, DIMENSION (10) :: impdo !implied do loop eg
REAL, DIMENSION (3) :: expres !expression eg
REAL, DIMENSION (9) :: myarray !array eg
INTEGER :: i
Let consider the same array but this time using the ORDER
specifier
INTEGER, DIMENSION(2,2) :: myarray
myarray = RESHAPE ((/1,2,3,4/),(/2,2/),ORDER=(/2,1/))
PRINT*, myarray
the output is 12
34
This time the array is filled up in row major form, (i.e fixing a
fixing and assigned the columns before moving to next row) this is
specified by the ORDER=(/2,1/) specifier. The default ordering
is, of course, ORDER=(/1,2/).
The ORDER keyword is necessary because some optional
arguments are missing. In this case PAD is missing.
Programming with Fortran II
Fortran Array
The RESHAPE Intrinsic Function - examples
Implied DO loop
Example
PROGRAM myown
IMPLICIT NONE
REAL, ALLOCATABLE, DIMENSION(:):: myvec ! vector array
INTEGER :: check var, xval
PRINT*,’enter the extent of the array’ ! size of vector
READ*,xval
ALLOCATE(myvec(xval), STAT=check var)
IF (check var/=0) THEN ! to check for correct dimension
PRINT*, ’not enough memory’
END IF
PRINT*,’enter the elements of the array’
READ*,myvec ! assign values to the array myvec
PRINT*,’array size is’, size(myvec), ’and elements are’, myvec
END PROGRAM myown
Programming with Fortran II
Fortran Array
Dynamic Arrays - Allocatable Arrays
OPEN statement
The OPEN statement is used to connect a named file to a logical
unit and to specify certain properties for that file which differ from
the defaults. It can be used to create or connect to an existing file.
The syntax is
OPEN([UNIT=]<integer>,FILE=<filename>,ERR=<label>, &
STATUS=<status>,ACCESS=<method>,ACTION=<mode>)
where
UNIT=< integer > specifies a numeric reference for the named file. The
number must be one that is not currently in use.
FILE=< filename > gives the filename to be associated with the logical
unit. The name must match exactly with the actual filename if you are
reading from existing file
ERR=< label > specifies a numeric label where control should be
transferred if there is an error opening the named file.
Programming with Fortran II
Fortran File input and output
File input/output
READ statement
The READ statement includes the keyword READ, followed by a
set of parentheses containing pertinent information, followed by a
list of variables (separated by commas). The READ statement is
used to read in data from a file.
The simplest syntax is as follows
READ(UNIT=< unit >, FMT =< format >) < data list >
where
unit - Set to be the unit number of the opened file
format - You can specify a string of formatting characters that
describe how the data is arranged in the file or use the default
FMT=*.
data list - The declared data types that is to be read from the data
file separated by commas.
Programming with Fortran II
Fortran File input and output
File input/output
The READ statement can read input values into a set of variables
from the keyboard.
The READ statement has the following forms:
READ (*,*) var1, var2, ..., varn
This form starts with READ(*,*), followed by a list of variable
names, separated by commas. The computer will read values from
the keyboard successively and puts the value into the variables.
READ (*,*)
It does not read in anything (to skip a whole line of data). It is
useful in reading data file headers.
!This READ(*,*) is similar to the already know input statement
READ*
Programming with Fortran II
Fortran File input and output
File input/output
WRITE statement
The WRITE statement includes the keyword WRITE, followed by a
set of parentheses containing pertinent information, followed by a
list of variables (separated by commas). The write command is
used to write data to a file
The simplest syntax is as follows
WRITE(UNIT=< unit >, FMT =< format >) < data list >
where
unit - Set to be the unit number of the opened file
format - You can specify a string of formatting characters that
describe how the data is to be written to the file or use the default
FMT=*.
data list - The declared data types that is to be written into the
data file separated by commas.
Programming with Fortran II
Fortran File input and output
File input/output
CLOSE statement
Execution of a CLOSE statement terminates the connection of a
file to a unit. Any connections not closed explicitly by a CLOSE
statement are closed by the operating system when the program
terminates, unless an error condition has terminated the program.
In its simplest form the CLOSE statement requires a unit number
(of a file already open)
The syntax is
CLOSE (UNIT=unit number)
where unit number refers to the unit number of the opened file.
For example to close a file opened with unit 10:
CLOSE (10)
CLOSE (UNIT=10)
The above CLOSE statements are equivalent
Programming with Fortran II
Fortran File input and output
Reading Data from a file
PROGRAM examp1
!this program read input data from a file and write output in another file
IMPLICIT NONE
INTEGER, DIMENSION(4,4) ::mydata !4x4 array declaration
INTEGER ::i,j
OPEN (20, FILE=’examp1.txt’,ACTION=’READ’) !input file
OPEN (30, FILE= ’output1.txt’, ACTION=’WRITE’) !output file
DO i=1,4
READ (20,*) (mydata(i,j),j=1,4) !implied do loop
WRITE (30,*)(mydata(i,j),j=1,4) !write into the file assigned 30
END DO
WRITE(*,*) MAXVAL(mydata) !maximum value of the data
WRITE(*,*) MAXLOC(mydata) !location of maximum value
WRITE(*,*) MINVAL(mydata) !maximum value of the data
WRITE(*,*) MINLOC(mydata) !location of minimum value
WRITE(*,*)TRANSPOSE(mydata) !transpose of the matrix
WRITE(*,*) SUM (mydata) !sum of the whole data
WRITE(*,*)SUM (mydata,1) !sum along each column
END PROGRAM examp1
Programming with Fortran II
Fortran File input and output
Reading Data from a file - example2
PROGRAM examp2
IMPLICIT NONE
INTEGER, DIMENSION(4,4) ::mydata !4x4 array declaration
INTEGER ::i,j
OPEN (20, FILE=’examp1.txt’,ACTION=’READ’) !input file
OPEN (30, FILE= ’output1.txt’, ACTION=’WRITE’) !output file
!————————————————————————–
READ(20,*) !to read the header (skip 1st line of data)
!—————————————————————————
DO i=1,4
READ (20,*) (mydata(i,j),j=1,4) !implied do loop
WRITE (30,*)(mydata(i,j),j=1,4) !write into the file assigned 30
END DO
WRITE(*,*) MAXVAL(mydata) !maximum value of the data
WRITE(*,*) MAXLOC(mydata) !location of maximum value
WRITE(*,*) MINVAL(mydata) !maximum value of the data
WRITE(*,*) MINLOC(mydata) !location of minimum value
END PROGRAM examp2
Programming with Fortran II
Fortran File input and output
Reading Data from a file - example3
PROGRAM examp3
! !this program read input data from a file
IMPLICIT NONE
INTEGER, PARAMETER :: nrow = 7 !total # of rows in the data
CHARACTER(LEN=10), DIMENSION (nrow) :: myname !name
INTEGER, DIMENSION (nrow) ::age !age declaration
REAL, DIMENSION (nrow) :: mark !mark declaration
INTEGER ::i !loop iterator
OPEN (50, FILE=’examp3.txt’,ACTION=’READ’) !input file
OPEN (5, FILE= ’output3.txt’, ACTION=’WRITE’) !output file
READ (50,*) !to read the header
DO i=1,nrow
READ(50,*) myname(i), age(i), mark(i) !note the positions
WRITE(5,*) myname(i), age(i), mark(i) !write output to file
END DO
!do your analysis here with the data
CLOSE(50) !close input file
CLOSE(5) !close output file
END PROGRAM examp3
Programming with Fortran II
Fortran File input and output
Reading Data from a file - using allocatable array
PROGRAM examp5
!how to read/write from/into file in a different directory
IMPLICIT NONE
CHARACTER (LEN = *), PARAMETER :: &
dir=”/home/ohene/Desktop/” !path to data declared as dir
INTEGER, PARAMETER :: nrow=4, ncol=4 !# of rows and columns
INTEGER, DIMENSION(nrow,ncol) :: mydata !data declaration
INTEGER ::i, j !loop iterators
OPEN(1,FILE=dir//’examp5.txt’,ACTION=’READ’) !open input file
OPEN(5,FILE=dir//’output5.txt’,ACTION=’WRITE’) !open outputfile
DO i=1,nrow
READ(1,*) (mydata(i,j),j = 1,ncol) !read data from file
WRITE(5,’(4(I2, 2x))’)(mydata(i,j), j= 1,ncol) !write data
END DO
!Do your analysis with the data here
CLOSE(1); CLOSE(5) !close files
END PROGRAM examp5
Programming with Fortran II
Fortran File input and output
Practical session
Example ::
Seasonal mean
Inter-seasonal variabilities
Using Gunplot to plot the output
Programming with Fortran II (MET 254) eoasare
Fortran File input and output
Lab1
rain − rain
rain
where rain is monthly recorded rainfall and rain is the mean rainfall
over the period (2009 - 2013)
GNUPLOT can display the manuals for its commands e.g. type help plot to get
information on the plot command
Commands can be shortened e.g. rep instead of replot or p instead of plot or lt
instead of linetype
reset restores the defaults If you want to use more than one GNUPLOT
command in one line, you have to separate the commands by semicolon (;)
GNUPLOT comments start with #
Start GNUPLOT by typing gnuplot on the terminal, in this case you want to use
GNUPLOT interactively
By default, GNUPLOT will plot the data using points
To start GNUPLOT, make sure you are in the ”data“ directory first, else you
will have to specify the path to the file
GNUPLOT not only reads data from files, it can also plot analytical functions
GNUPLOT has several formatting parameters that can be used to change the
appearance of a plot. These parameters are accessed using the set command.
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
You may use a # character to comment a line out. If you wish to wrap a
command over more than one line, add a \ character to the end of the previous
line. For example:
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
Output formats
By default, screens are displayed to the standard output. The set output
command redirects the display to the specified file or device.
Use set terminal to tell gnuplot what kind of output to generate. Several
terminals have many additional options. You can check your current terminal
with show terminal
The simple synatx is
The previous is just for gnuplot environemnt, however we can also use the shell
for gnuplot scripts
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
If missing data exist in data series, you can specified to leave those missing
values
set datafile missing ”put the missing value here“
Example
set datafile missing ”-9999“
set datafile missing ”NAN“
Programming with Fortran II (MET 254) eoasare
Introduction to Gnuplot
basics
Example
if the data is of the form
#Date MFT
2010/Jan 37 49 86
2010/Feb 12 17 29
... .... .... ....
... .... .... ....
2012/Jul 67 99 166
Then xtics can be set as follows
set xdata time # set axis for data format
set timefmt ”%Y/%b” # defined the format as in the data
set format x ”%Y/%b” # set xtics format
set xrange[”2010/Jan”:”2012/Jul”] # set xtics range
The data can be plotted afterwards