AN INTRODUCTION TO FORTRAN 90 LECTURE 2. Consider the following system of linear equations: a x + a x + a x = b

Size: px
Start display at page:

Download "AN INTRODUCTION TO FORTRAN 90 LECTURE 2. Consider the following system of linear equations: a x + a x + a x = b"

Transcription

1 AN INTRODUCTION TO FORTRAN 90 LECTURE 2 1. Fortran 90. Arrays, functions and subroutines. 2. Scientific plotting. Gnuplot 1 Each coefficient and variable is a scalar. Lengthy and cumbersome! Program Scalar Implicit None real a11,a12,a13,b1 real a21,a22,a23,b2 real a31,a32,a33,b3 real x1,x2,x3 Execution part Arrays. Introduction Consider the following system of linear equations: a x + a x + a x = b a x + a x + a x = b a x + a x + a x = b Coefficients and variables defined as matrices and vectors. Short and clear! Program Array Implicit None real, dimension(1:3,1:3) :: A real, dimension(1:3) :: B real, dimension(1:3) :: X Execution part Rank-two array A has nine components: A(1,1) A(1,2) A(1,3) A(2,1) A(2,2) A(3,2) A(3,1) A(3,2) A(3,3) Rank-one array B has three components: B(1) B(2) B(3) In Fortran 90 all elements of an array are of the same type and have the same name. They are distinguished by array indices, which are consecutive integers. Commas separate the array dimensions, colons define the array extent. 2

2 Arrays. General information The first array element is 1, i.e. A(15) A(1) to A(15). Array sizes must be specified by INTEGER constants. The maximum number of dimensions (rank) is 7, i.e. B(4,5,3,6,8,5,10) The shape function returns the number of elements in each dimension. Try PRINT *, SHAPE(B). Empty for a scalar. more useful definition of arrays integer, parameter :: N=1, M=10, P=20 real, dimension(n:m) :: A real, dimension(m:p,n:p) :: B! Declares the extent of the array Integer constants N, M and P define the extent of the array along each dimension. Assigning values to arrays real, dimension(5), parameter :: B=/1.,-3.,-4., 3.,-3.5/ integer, dimension(5,10) :: A integer i,j do j=1,10 do i=1,5 A(i,j)=i+j do do! Assigns constant values to array B The reverse order of the do loops would produce the so-called bad cache locality and significant worsening in the code performance! 3 Each array element is a variable just like any scalar variable. Array elements may be used anywhere in executable statements where a scalar variable of the same type would be used. = 3 Program Summation S X i real, dimension(3) :: X i= 1 real S Integer i S=0. Do i=1,3! The array index must not exceed S = S + X(i)! the array extent, i.e. 3 End do End Program Multiplication Real*8, dimension(1:3) :: A Real*8, dimension(1:2) :: B,C Integer i, j, k do i=1,3 do j=1,2 do k=1,3 C(i,j) = C(i,j) + A(i,k)*B(k,j) do do do C 3 ij = Aik Bkj k = 1 do i=1,n do j=1,n C(i,j)=DOT_PRODUCT(A(i,1:n),B(1:n,j)) do do Array operations in Fortran 90 S=sum(X)! returns the sum of array X A=maxval(X)! returns the maximum value of array X B=minval(X)! returns the minimum value of array X Indexed summation do i=1,n do j=1,n C(j,i) = A(j,i) + B(j,i) do do Matrix summation C = A + B operation on the rows, columns, or a sub-matrix of a matrix real*8, dimension(3,3) :: A real*8, dimension(2,2) :: B real*8, dimension(3) :: v(3) v(:) = A(:,1)! set v equal to the first column of A v(:) = A(1,:)! set v equal to the first row of A B(:,:) = A(1:2,1:2)! B is the upper 2x2 part of A 4

3 Input / output operations read( UNIT, FORMAT ) write( UNIT, FORMAT ) item1, item2, item1, item2, The UNIT is a number which has an association with a particular device. The device can be the TERMINAL or a FILE. The UNIT is an INTEGER, generally between 1 and 99. Standard FORTRAN reserves two UNIT numbers for I/O to user. They are: UNIT = 5 for INPUT from the keyboard with the READ statement, i.e., read(5,*) x reads from the keyboard the value of x UNIT = 6 for OUTPUT to the screen with the WRITE statement, i.e., write(6,*) x writes the value of x to the terminal. The FORMAT identifier is used to control the appearance of the I/O statements and it generally has one of two forms 1) An asterisk (*) indicates free format. 2) A character string containing the format descriptors Program output real x real*8 y x=1.2 y=1.3d-2 write(6,*) x, y The general I/O statement (spaces added for clarity) Program output real x real*8 y x=1.2 y=1.3d-2 write(6, (2F10.3) ) x, y Program output real x real*8 y logical a x=1.2 y=1.3d-8 write(6, (2E10.3,L4) ) x, y, a D E E-7 F Other descriptors: I for the output of integer variables: I5 five digit integer A for the output of a character string: A10 a character string with 10 characters L for the output of logical variables and many other variants and combinations. 5 Input from and output to external files The open command is used to open files - that is, it makes files available so that Fortran can read or write to them. The simplest form of the command is open (unit = number, file = "name, specifications) open (unit=10, file = /scratch/student1/work/scores.txt, status= old )! Opens an existing file scores.txt open (11, file = ~/test.txt,status= unknown, position= app )! Opens a new file (if not existed) or existed file and apps new data to the of the file. Communication with the opened file is done via the write statement write(unit=10, (2F10.3) ) x, y! Unit numbers must agree, unit=10, not 12 or 14! write(11,*) z when the I/O operations with the file are finished, the close statement must follow to close the file Close(10,11)! Closes both files altogether 6

4 Allocatable arrays Sometimes the extent of the array may not be known a priori. Example: reading data from a file. Program data1 integer, parameter :: Nmax=1000 real, dimension(nmax) :: X integer i, N open(10,file= data.dat,status= old ) read(10,*) N! reads the file dimension do i=1, N read(10,*) X(i) do close(10) print,* N! reads data! If N<<Nmax waste of memory Program data2 real, dimension(:), allocatable :: X integer i, N, test open(10,file= data.dat,status= old ) read(10,*) N! reads the file dimension Allocate( X(N), stat=test )! Allocates array of size N If (test.ne.0) write(6,*) Error with array allocation do i=1, N read(10,*) X(i)! reads data do close(10) deallocate(x)! Clears memory The rank of an allocatable array is specified by the number of colons in the DIMENSION attribute. e.g. REAL, ALLOCATABLE, DIMENSION(:,:) :: Y! rank-two array The rule of thumbs: Do not use the allocatable attribute unless you really need to! Reason: 1) the compiler has a difficulty to optimize allocatable arrays. 2) messing with allocate / deallocate statements can produce phantom arrays, with a much heavier burden on the computer memory as compared to static arrays. 7 SELECT CASE Statement SELECT CASE (selector) CASE (label-list-1) statements-1 CASE (label-list-2) statements-2 CASE (label-list-n) statements-n CASE DEFAULT statements-default END SELECT selector is an expression whose result is of type INTEGER, CHARACTER or LOGICAL (i.e., no REAL type can be used for the selector). The rule of executing the SELECT CASE statement goes as follows: 1. The selector expression is evaluated 2. If the result is in label-list-i, then the sequence of statements in statements-i are executed, followed by the statement following END SELECT 3. If the result is not in any one of the label lists, there are two possibilities: a) if CASE DEFAULT is there, then the sequence of statements in statements-default are executed, followed by the statement following END SELECT b) if there is no CASE DEFAULT is not there, the statement following END SELECT is executed. INTEGER :: month SELECT CASE (month) CASE (12,1,2) write (*,*) 'Winter' CASE (3:5) write (*,*) 'Spring' CASE (6:8) write (*,*) 'Summer' CASE (9:11) write (*,*) 'Autumn' CASE DEFAULT write (*,*) 'Error: Something is wrong with your date' END SELECT 8

5 Derived types in Fortran 90 Fortran 90 supports five standard types for constants/variables: integer, real, complex, character, and logical. Besides, you can define a new type as shown in the example below. Suppose we have a grid with N x N grid cells. Each grid is characterized by x and y coordinates Temperature T density rho Program Newtype implicit NONE integer, parameter :: N=100 integer i type :: Grid! Declaring a new type Grid sequence! Forces to store the data in the memory in sequence real*8, dimension(1:n,1:n) :: T, rho! Elements of the derived type real*8, dimension(1:n) :: x, y type Grid type(grid) :: Cell! Declaring a variable Cell with type Grid Do i=1,n Cell%x(i)=i! Assigning values to the elements of the variable Cell Cell%y(i)=i Cell%T(i,i)=100.d0 Enddo Elements of derived types are accessed with the "%" operator 9 Functions in Fortran 90 In addition to intrinsic functions, Fortran allows you to design your own functions. A Fortran function has the following syntax: type FUNCTION function-name (arg1, arg2,..., argn) Declaration of modules IMPLICIT NONE declaration of constants and variables execution part END [FUNCTION function-name] type gives the type of the function value (i.e., INTEGER, REAL, LOGICAL and CHARACTER) function-name is the name you assign to the function, it must be unique. arg1, arg2, are so-called dummy arguments, which are the means of communication of the function with outer program units. Dummy arguments must be variable names, arithmetic expressions, or names of other functions/subroutines. Communication with other program units can also be done via the list of modules. The execution part must contain at least one operator function-name =. In other words, you must calculate the result of the function at least once. Functions can be internal or external to another program unit. For internal functions, [FUNCTION function-name] should be placed at the of the function declaration Simple example of external function INTEGER FUNCTION Sum(a, b, c) IMPLICIT NONE INTEGER, INTENT(IN) :: a, b, c Sum = a + b + c END Dummy arguments a, b, c must be explicitly declared (otherwise, how would the compiler know the type of the arguments?). The INTENT(IN) specification tells the compiler that the arguments cannot be reassigned values inside the function. 10

6 Example of internal function Linear interpolation of a tabulated function y=f(x) Program Tabular real, dimension(5), parameter :: x=(/1.,2.,3.,4.,5./) real, dimension(5), parameter :: y=(/1.,3.,6.,12.,21./) Real xdot,ydot integer i Write(6,*) 'input x coordinate between 1 and 5' Read(5,*) xdot i=1 Do while (x(i).le.xdot) i=i+1 Enddo ydot=lininter(x(i-1),x(i),y(i-1),y(i),xdot) write(6,*) ydot! Declaration of internal function begins CONTAINS Real Function LinInter(x1,x2,y1,y2,x) implicit NONE Real x1,x2,y1,y2,x If (x1.ne.x2) then LinInter= y1+(x-x1)*(y2-y1)/(x2-x1) Else LinInter=y1 Endif function LinInter! Declaration of internal function s! Tabulated x-data! Tabulated y-data! Reads the argument x! Localizes a pair of x-data that bound the argument x! Calculates the linearly interpolated function y 11 Comparison of internal and external functions Internal function Program Tabular real, dimension(5), parameter :: x=(/1.,2.,3.,4.,5./) real, dimension(5), parameter :: y=(/1.,3.,6.,12.,21./) Real xdot,ydot integer i Write(6,*) 'input x coordinate between 1 and 5' Read(5,*) xdot i=1 Do while (x(i).le.xdot) i=i+1 Enddo ydot=lininter(x(i-1),x(i),y(i-1),y(i),xdot) write(6,*) ydot! Declaration of internal function begins CONTAINS Real Function LinInter(x1,x2,y1,y2,x) implicit NONE Real x1,x2,y1,y2,x If (x1.ne.x2) then LinInter= y1+(x-x1)*(y2-y1)/(x2-x1) Else LinInter=y1 Endif function LinInter! Declaration of internal function s All variables of program Tabular (called global variables) are visible by the internal function. External function Program Tabular real, dimension(5), parameter :: x=(/1.,2.,3.,4.,5./) real, dimension(5), parameter :: y=(/1.,3.,6.,12.,21./) Real xdot,ydot Real, external :: LinInter integer i Write(6,*) 'input x coordinate between 1 and 5' Read(5,*) xdot i=1 Do while (x(i).le.xdot) i=i+1 Enddo ydot=lininter(x(i-1),x(i),y(i-1),y(i),xdot) write(6,*) ydot!. Declaration of external function begins Real Function LinInter(x1,x2,y1,y2,x) implicit NONE Real x1,x2,y1,y2,x If (x1.ne.x2) then LinInter= y1+(x-x1)*(y2-y1)/(x2-x1) Else LinInter=y1 Endif The external function knows nothing about the global variables in program Tabular. Communication is performed exclusively via the list of arguments. Good 12 practice even in the case of internal functions!

7 Subroutines in Fortran 90 The syntax of subroutines is similar to that of the functions. SUBROUTINE subroutine-name (arg1, arg2,..., argn) Declaration of modules IMPLICIT NONE declaration of constants and variables execution part END [SUBROUTINE subroutine-name] A subroutine, just like the main program, must have a name and this name is used to call the subroutine during program execution. The main purpose of subroutines is to perform a set of frequently used operations. 13 Example of internal subroutine Finding the real roots of a quadratic equation Program RealRoots real x1, x2, a, b, c, Disc write(6,*) Input parameters a, b, and c read(5,*) a, b, c Disc=b*b-4*a*c If (Disc.ge.0.) then x1=(-b+sqrt(disc)) / (2*a) x2=(-b-sqrt(disc)) / (2*a) write(6, (A25,2F8.2) ) The real roots are, x1, x2 Else write(6,*) No real roots Endif End You need to run the code all over again, if the real roots are not found Note that the names of the dummy and actual arguments may not coincide. However, the number and type of both dummy and actual arguments must coincide! Internal variables x1, x2, Disc are not visible in the main program. However, the global variables a1, b1, c1 are visible in the internal subroutine. If global and internal variables have the same name, the internal ones take the precedence (prevail). Program RealRoots real a1, b1, c1 logical flag Do while (.not.flag) write(6,*) Input parameters a, b, and c read(5,*) a1, b1, c1 Call RealRoot(a1,b1,c1,flag)! Calls the internal subroutine Enddo! declaration of internal subroutines begins. CONTAINS Subroutine RealRoot(a,b,c,flag) real, intent(in) :: a, b, c logical, intent(out) :: flag! flag must be assigned a value real x1,x2,disc! Internal variables Disc=b*b - 4*a*c If (Disc.ge.0.) then x1=(-b+sqrt(disc)) / (2*a) x2=(-b-sqrt(disc)) / (2*a) write(6, (A28,2F8.2) ) The real roots are, x1, x2 flag=.true. Else write(6,*) No real roots flag=.false. Endif subroutine RealRoot!.. Declaration of internal subroutines s End 14

8 Functions/subroutines as dummy arguments Dummy arguments in Fortran can be not only variables and arithmetic expressions but also the names of other EXTERNAL functions/subroutines. This feature is very handy when one needs to frequently call different functions of similar form. The following code provides an example. External functions need to have the same number of arguments! Program Dummy Real x,y Real, external :: One,Two! declares external functions! Call Evaluate(One,x,y) Call Evaluate(Two,x,y)! CONTAINS Subroutine Evaluate(funcName,x,y) Real, intent(in) :: funcname,x Real, intent(out) :: y y = funcname(x) + funcname(2*x) +1./funcName(-x) End!.. External function Real function One(x) Real, intent(in) ::x one=x**2 + sin(x) End!. Yet another external function Real function Two(x) Real, intent(in) :: x two= /x**2 tan(x) 15 Modules in Fortran 90 Purpose: Sharing variables, functions and subroutines between different program units MODULE module-name declaration of constants and variables [CONTAINS declaration of functions and subroutines] END MODULE module-name MODULE constants implicit NONE Real*8, parameter :: Msol = d33 Real*8, parameter :: parsec = d18 END MODULE constants PROGRAM main USE constants, ONLY: pi write (6,*) 'Pi = ', pi END 16

9 Procedure overloading Procedure overloading is used a lot in modular programming. Basically, the same name is given to two or more functions or subroutines. The program distinguishes between them based on the signature of the call made. For example, one could overload two subroutines to be called setzcut, with one taking an argument of type real and the other taking an argument of type integer. If I call setzcut passing an integer, then the subroutine taking an integer is called

10 19 20

11 21 22

12 23 Assignment 2 Introduction to Fortran 90 Lecturer: Dr. Eduard Vorobyov Due date: April 9, 2012 (zero tolerance!) Write a Fortran 90 code for the numerical integration of the following definite integral: b 2 1 x x a dx (1) Using the exted Simpson s rule: b a f ( x) dx = h f ( x1 ) + f ( x2 ) + f ( x3) + f ( x4 ) + K K+ f ( xn 2) + f ( xn 1) + f ( xn ) + f ( xn+ 1) Where x 1, x 2, x n+1 are equally spaced abscissas and, in particular, x 1 = a and x n+1 = b. The integration step is calculated as h = (b-a) / n and x i = a+(i-1)*h, i=1, n+1. Calculate the integral (1) for a=0 and b=1 with relative accuracy Start the integration with n = 10 and gradually increase n (which must be an even number!) until the desired accuracy is achieved. Ideally, the code should make use of functions and subroutine calls. 24

13 Graphical representation of numerical integration. Trapezoidal rule f(x 2 ) f(x 1 ) S 1 S 2 S n h x 1 x 2 x n x n+1 h S = f x + f x 2 ( ( ) ( )) xn+ 1 x 1 ( ) n = i + ( 3 ) i= 1 f x dx S O h Note that n+1 is the number of integration points and n is the number intervals. The greater n, the better the accuracy of the integration. This fact can be used to achieve a desired accuracy by increasing the value of n and calculating the relative error between the new and old estimate of the integral. Evaluation criteria: 1) Correctness. The code must give the correct result! 2) Completeness. All tasks in the assignments must be fulfilled. 3) Conciseness. The code must be as short as possible. Remember, the shorter your code, the longer your brains! 4) Versatility. You should use as many Fortran features as possible to demonstrate your knowledge. 5) Clearness. The code must be written clearly with necessary comments included so that others could understand the code. What should be presented. 1) A printed version of the code with the results of calculations. 2) An electronic version of the source code (not executable!) to be ed to eduard.vorobiev@univie.ac.at 26

AMath 483/583 Lecture 8

AMath 483/583 Lecture 8 AMath 483/583 Lecture 8 This lecture: Fortran subroutines and functions Arrays Dynamic memory Reading: class notes: Fortran Arrays class notes: Fortran Subroutines and Functions class notes: gfortran flags

More information

Subroutines, Functions and Modules

Subroutines, Functions and Modules Subroutines, Functions and Modules Subdividing the Problem Most problems are thousands of lines of code. Few people can grasp all of the details. Good design principle: Exhibit the overall structure in

More information

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Using Monte Carlo to Estimate π using Buffon s Needle Problem An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s. Here s the problem (in a simplified form). Suppose

More information

Review More Arrays Modules Final Review

Review More Arrays Modules Final Review OUTLINE 1 REVIEW 2 MORE ARRAYS Using Arrays Why do we need dynamic arrays? Using Dynamic Arrays 3 MODULES Global Variables Interface Blocks Modular Programming 4 FINAL REVIEW THE STORY SO FAR... Create

More information

An Introduction to Fortran

An Introduction to Fortran An Introduction to Fortran Sylvia Plöckinger March 10, 2011 Sylvia Plöckinger () An Introduction to Fortran March 10, 2011 1 / 43 General Information Find this file on: http://homepage.univie.ac.at/nigel.mitchell/numprac/

More information

Lecture V: Introduction to parallel programming with Fortran coarrays

Lecture V: Introduction to parallel programming with Fortran coarrays Lecture V: Introduction to parallel programming with Fortran coarrays What is parallel computing? Serial computing Single processing unit (core) is used for solving a problem One task processed at a time

More information

Review Functions Subroutines Flow Control Summary

Review Functions Subroutines Flow Control Summary OUTLINE 1 REVIEW 2 FUNCTIONS Why use functions How do they work 3 SUBROUTINES Why use subroutines? How do they work 4 FLOW CONTROL Logical Control Looping 5 SUMMARY OUTLINE 1 REVIEW 2 FUNCTIONS Why use

More information

Allocating Storage for 1-Dimensional Arrays

Allocating Storage for 1-Dimensional Arrays Allocating Storage for 1-Dimensional Arrays Recall that if we know beforehand what size we want an array to be, then we allocate storage in the declaration statement, e.g., real, dimension (100 ) :: temperatures

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Learn about multi-dimensional (rank > 1) arrays Learn about multi-dimensional array storage Learn about the RESHAPE function Learn about allocatable arrays & the ALLOCATE and DEALLOCATE

More information

Introduction to Programming with Fortran 90

Introduction to Programming with Fortran 90 Introduction to Programming with Fortran 90 p. 1/?? Introduction to Programming with Fortran 90 Array Concepts Nick Maclaren Computing Service nmm1@cam.ac.uk, ext. 34761 November 2007 Introduction to Programming

More information

41391 High performance computing: Miscellaneous parallel programmes in Fortran

41391 High performance computing: Miscellaneous parallel programmes in Fortran 1391 High performance computing: Miscellaneous parallel programmes in Fortran Nilas Mandrup Hansen, Ask Hjorth Larsen January 19, 0 1 Introduction This document concerns the implementation of a Fortran

More information

INTRODUCTION TO FORTRAN PART II

INTRODUCTION TO FORTRAN PART II INTRODUCTION TO FORTRAN PART II Prasenjit Ghosh An example: The Fibonacci Sequence The Fibonacci sequence consists of an infinite set of integer nos. which satisfy the following recurrence relation x n

More information

Our Strategy for Learning Fortran 90

Our Strategy for Learning Fortran 90 Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data

More information

Subprograms. FORTRAN 77 Chapter 5. Subprograms. Subprograms. Subprograms. Function Subprograms 1/5/2014. Satish Chandra.

Subprograms. FORTRAN 77 Chapter 5. Subprograms. Subprograms. Subprograms. Function Subprograms 1/5/2014. Satish Chandra. FORTRAN 77 Chapter 5 Satish Chandra satish0402@gmail.com When a programs is more than a few hundred lines long, it gets hard to follow. Fortran codes that solve real research problems often have tens of

More information

Array Processing { Part II. Multi-Dimensional Arrays. 1. What is a multi-dimensional array?

Array Processing { Part II. Multi-Dimensional Arrays. 1. What is a multi-dimensional array? Array Processing { Part II Multi-Dimensional Arrays 1. What is a multi-dimensional array? A multi-dimensional array is simply a table (2-dimensional) or a group of tables. The following is a 2-dimensional

More information

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain

Introduction to Matlab. By: Dr. Maher O. EL-Ghossain Introduction to Matlab By: Dr. Maher O. EL-Ghossain Outline: q What is Matlab? Matlab Screen Variables, array, matrix, indexing Operators (Arithmetic, relational, logical ) Display Facilities Flow Control

More information

Chapter 4. Fortran Arrays

Chapter 4. Fortran Arrays Chapter 4. Fortran Arrays Fortran arrays are any object with the dimension attribute. In Fortran 90/95, and in HPF, arrays may be very different from arrays in older versions of Fortran. Arrays can have

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Learn a simple sorting algorithm Understand how compilation & linking of separate main program and subprogram files are accomplished. Understand how to use subprograms to create

More information

SHAPE Returns the number of elements in each direction in an integer vector.

SHAPE Returns the number of elements in each direction in an integer vector. Chapter 5: Arrays An advantage fortran has over other programming languages is the ease with which it handles arrays. Because arrays are so easy to handle, fortran is an ideal choice when writing code

More information

Introduction to Modern Fortran

Introduction to Modern Fortran Introduction to Modern Fortran p. 1/?? Introduction to Modern Fortran Advanced Use Of Procedures Nick Maclaren nmm1@cam.ac.uk March 2014 Introduction to Modern Fortran p. 2/?? Summary We have omitted some

More information

1 Introduction to MATLAB

1 Introduction to MATLAB 1 Introduction to MATLAB 1.1 Quick Overview This chapter is not intended to be a comprehensive manual of MATLAB R. Our sole aim is to provide sufficient information to give you a good start. If you are

More information

7. Procedures and Structured Programming

7. Procedures and Structured Programming 7. Procedures and Structured Programming ONE BIG PROGRAM external procedure: separated small and reusable program units to conduct individual subtasks smaller main program Each program unit can be debugged

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 4: Programming in Matlab Yasemin Bekiroglu (yaseminb@kth.se) Florian Pokorny(fpokorny@kth.se) Overview Overview Lecture 4: Programming in Matlab Wrap Up More on Scripts and Functions Wrap Up Last

More information

Edit Descriptors. Decimal form. Fw.d Exponential form Ew.d Ew.dEe Scientific form ESw.d ESw.dEe Engineering form ENw.d ENw.dEe.

Edit Descriptors. Decimal form. Fw.d Exponential form Ew.d Ew.dEe Scientific form ESw.d ESw.dEe Engineering form ENw.d ENw.dEe. Format Edit Descriptors The tedious part of using Fortran format is to master many format edit descriptors. Each edit descriptor tells the system how to handle certain type of values or activity. Each

More information

1 Introduction to MATLAB

1 Introduction to MATLAB 1 Introduction to MATLAB 1.1 General Information Quick Overview This chapter is not intended to be a comprehensive manual of MATLAB R. Our sole aim is to provide sufficient information to give you a good

More information

(Refer Slide Time: 1:27)

(Refer Slide Time: 1:27) Data Structures and Algorithms Dr. Naveen Garg Department of Computer Science and Engineering Indian Institute of Technology, Delhi Lecture 1 Introduction to Data Structures and Algorithms Welcome to data

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up More on Scripts and Functions Basic Programming Lecture 2 Lecture 3 Lecture 4 Wrap Up Last time Loading data from file: load( filename ) Graphical input and

More information

Introduction to Fortran95 Programming Part II. By Deniz Savas, CiCS, Shef. Univ., 2018

Introduction to Fortran95 Programming Part II. By Deniz Savas, CiCS, Shef. Univ., 2018 Introduction to Fortran95 Programming Part II By Deniz Savas, CiCS, Shef. Univ., 2018 Summary of topics covered Logical Expressions, IF and CASE statements Data Declarations and Specifications ARRAYS and

More information

Fortran. (FORmula TRANslator) History

Fortran. (FORmula TRANslator) History Fortran (FORmula TRANslator) History FORTRAN vs. Fortran 1954 FORTRAN first successful high level language John Backus (IBM) 1958 FORTRAN II (Logical IF, subroutines, functions) 1961 FORTRAN IV 1966 FORTRAN

More information

FORTRAN 90: Functions, Modules, and Subroutines. Meteorology 227 Fall 2017

FORTRAN 90: Functions, Modules, and Subroutines. Meteorology 227 Fall 2017 FORTRAN 90: Functions, Modules, and Subroutines Meteorology 227 Fall 2017 Purpose First step in modular program design Cannot always anticipate all of the steps that will be needed to solve a problem Easier

More information

Interfacing With Other Programming Languages Using Cython

Interfacing With Other Programming Languages Using Cython Lab 19 Interfacing With Other Programming Languages Using Cython Lab Objective: Learn to interface with object files using Cython. This lab should be worked through on a machine that has already been configured

More information

Old Questions Name: a. if b. open c. output d. write e. do f. exit

Old Questions Name: a. if b. open c. output d. write e. do f. exit Old Questions Name: Part I. Multiple choice. One point each. 1. Which of the following is not a Fortran keyword? a. if b. open c. output d. write e. do f. exit 2. How many times will the code inside the

More information

Evaluating the polynomial at a point

Evaluating the polynomial at a point Evaluating the polynomial at a point Recall that we have a data structure for each piecewise polynomial (linear, quadratic, cubic and cubic Hermite). We have a routine that sets evenly spaced interpolation

More information

Fortran Coarrays John Reid, ISO Fortran Convener, JKR Associates and Rutherford Appleton Laboratory

Fortran Coarrays John Reid, ISO Fortran Convener, JKR Associates and Rutherford Appleton Laboratory Fortran Coarrays John Reid, ISO Fortran Convener, JKR Associates and Rutherford Appleton Laboratory This talk will explain the objectives of coarrays, give a quick summary of their history, describe the

More information

Introduction to MATLAB 7 for Engineers

Introduction to MATLAB 7 for Engineers PowerPoint to accompany Introduction to MATLAB 7 for Engineers William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2005. The McGraw-Hill Companies, Inc. Permission required for

More information

Chapter 8 :: Composite Types

Chapter 8 :: Composite Types Chapter 8 :: Composite Types Programming Language Pragmatics, Fourth Edition Michael L. Scott Copyright 2016 Elsevier 1 Chapter08_Composite_Types_4e - Tue November 21, 2017 Records (Structures) and Variants

More information

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011 Autumn 2015 Lecture 3, Simple C programming M. Eriksson (with contributions from A. Maki and

More information

Programming Tips for Plugins

Programming Tips for Plugins Programming Tips for Plugins Chad Neufeld Centre for Computational Geostatistics Department of Civil & Environmental Engineering University of Alberta Working in a university based research environment

More information

1. User-Defined Functions & Subroutines Part 1 Outline

1. User-Defined Functions & Subroutines Part 1 Outline User-Defined Functions Subroutines Part 1 Outline 1. User-Defined Functions Subroutines Part 1 Outline 2. Intrinsic Functions Are Not Enough 3. User-Defined Functions 4. A User-Defined Function for Mean

More information

Welcome. Modern Fortran (F77 to F90 and beyond) Virtual tutorial starts at BST

Welcome. Modern Fortran (F77 to F90 and beyond) Virtual tutorial starts at BST Welcome Modern Fortran (F77 to F90 and beyond) Virtual tutorial starts at 15.00 BST Modern Fortran: F77 to F90 and beyond Adrian Jackson adrianj@epcc.ed.ac.uk @adrianjhpc Fortran Ancient History (1967)

More information

In context with optimizing Fortran 90 code it would be very helpful to have a selection of

In context with optimizing Fortran 90 code it would be very helpful to have a selection of 1 ISO/IEC JTC1/SC22/WG5 N1186 03 June 1996 High Performance Computing with Fortran 90 Qualiers and Attributes In context with optimizing Fortran 90 code it would be very helpful to have a selection of

More information

Goals of this Lecture

Goals of this Lecture C Pointers Goals of this Lecture Help you learn about: Pointers and application Pointer variables Operators & relation to arrays 2 Pointer Variables The first step in understanding pointers is visualizing

More information

ISO/IEC : TECHNICAL CORRIGENDUM 2

ISO/IEC : TECHNICAL CORRIGENDUM 2 ISO/IEC 1539-1:2010 - TECHNICAL CORRIGENDUM 2 ISO/IEC/JTC1/SC22/WG5-N1957 Notes for WG5: Edits included in this document from the interpretations in N1932 as amended by 12-193 and 12-194 and in N1949 as

More information

Introduction to Fortran Programming. -Internal subprograms (1)-

Introduction to Fortran Programming. -Internal subprograms (1)- Introduction to Fortran Programming -Internal subprograms (1)- Subprograms Subprograms are used to split the program into separate smaller units. Internal subprogram is not an independent part of a program.

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand what function subprograms are Understand how to use function subprograms Understand the various kinds of REAL types Understand how to select precision in a processor

More information

NO CALCULATOR ALLOWED!!

NO CALCULATOR ALLOWED!! CPSC 203 500 EXAM TWO Fall 2005 NO CALCULATOR ALLOWED!! Full Name (Please Print): UIN: Score Possible Points Prog Points Part One 33 pts Part Two 30 pts Part Three 20 pts Part Four 25 pts Total 108 pts

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand what modules are Understand what module procedures are and how to use them Understand explicit and implicit interfaces Understand what automatic arrays are and how to

More information

Goals for This Lecture:

Goals for This Lecture: Goals for This Lecture: Understand the various kinds of REAL types Understand how to select precision in a processor independent manner Introduction to Makefiles Kinds of REAL variables The default REAL

More information

Introduction to Scientific Computing with Matlab

Introduction to Scientific Computing with Matlab Introduction to Scientific Computing with Matlab Matlab is an interactive system for numerical computations. It is widely used in universities and industry, and has many advantages over languages such

More information

Computers in Engineering. Moving From Fortran to C Michael A. Hawker

Computers in Engineering. Moving From Fortran to C Michael A. Hawker Computers in Engineering COMP 208 Moving From Fortran to C Michael A. Hawker Remember our first Fortran program? PROGRAM hello IMPLICIT NONE!This is my first program WRITE (*,*) "Hello, World!" END PROGRAM

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

Introduction to MATLAB for Engineers, Third Edition

Introduction to MATLAB for Engineers, Third Edition PowerPoint to accompany Introduction to MATLAB for Engineers, Third Edition William J. Palm III Chapter 2 Numeric, Cell, and Structure Arrays Copyright 2010. The McGraw-Hill Companies, Inc. This work is

More information

High Performance Fortran http://www-jics.cs.utk.edu jics@cs.utk.edu Kwai Lam Wong 1 Overview HPF : High Performance FORTRAN A language specification standard by High Performance FORTRAN Forum (HPFF), a

More information

SUBROUTINE subroutine-name (arg1, arg2,..., argn)

SUBROUTINE subroutine-name (arg1, arg2,..., argn) FORTRAN Subroutines Syntax Form 1 SUBROUTINE subroutine-name (arg1, arg2,..., argn) [specification part] [execution part] [subprogram part] subroutine-name Form 2 SUBROUTINE subroutine-name () [specification

More information

Chapter 3. Fortran Statements

Chapter 3. Fortran Statements Chapter 3 Fortran Statements This chapter describes each of the Fortran statements supported by the PGI Fortran compilers Each description includes a brief summary of the statement, a syntax description,

More information

Subroutines and Functions

Subroutines and Functions Subroutines and Functions Procedures: Subroutines and Functions There are two types of procedures: SUBROUTINE: a parameterized named sequence of code which performs a specific task and can be invoked from

More information

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation. Lab 4 Functions Introduction: A function : is a collection of statements that are grouped together to perform an operation. The following is its format: type name ( parameter1, parameter2,...) { statements

More information

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values

It can be confusing when you type something like the expressions below and get an error message. a range variable definition a vector of sine values 7_april_ranges_.mcd Understanding Ranges, Sequences, and Vectors Introduction New Mathcad users are sometimes confused by the difference between range variables and vectors. This is particularly true considering

More information

Parallel Programming in Fortran with Coarrays

Parallel Programming in Fortran with Coarrays Parallel Programming in Fortran with Coarrays John Reid, ISO Fortran Convener, JKR Associates and Rutherford Appleton Laboratory Fortran 2008 is now in FDIS ballot: only typos permitted at this stage.

More information

APPENDIX B. Fortran Hints

APPENDIX B. Fortran Hints APPENDIX B Fortran Hints This appix contains hints on how to find errors in your programs, and how to avoid some common Fortran errors in the first place. The basics on how to invoke the Fortran compiler

More information

Intrinsic Numeric Operations

Intrinsic Numeric Operations Intrinsic Numeric Operations The following operators are valid for numeric expressions: ** exponentiation (e.g., 10**2) evaluated right to left: 2**3**4 is evaluated as 2**(3**4) * and / multiply and divide

More information

Structured Programming. Dr. Mohamed Khedr Lecture 4

Structured Programming. Dr. Mohamed Khedr Lecture 4 Structured Programming Dr. Mohamed Khedr http://webmail.aast.edu/~khedr 1 Scientific Notation for floats 2.7E4 means 2.7 x 10 4 = 2.7000 = 27000.0 2.7E-4 means 2.7 x 10-4 = 0002.7 = 0.00027 2 Output Formatting

More information

2 Making Decisions. Store the value 3 in memory location y

2 Making Decisions. Store the value 3 in memory location y 2.1 Aims 2 Making Decisions By the end of this worksheet, you will be able to: Do arithmetic Start to use FORTRAN intrinsic functions Begin to understand program flow and logic Know how to test for zero

More information

Logical Expressions and Control Statements

Logical Expressions and Control Statements Logical Expressions and Control Statements Logical Data Logical values are true and false. In Fortran they must be written as: and Logical variables are declared with LOGICAL: LOGICAL :: Answer, Test Logical

More information

Computers in Engineering. Subroutines Michael A. Hawker

Computers in Engineering. Subroutines Michael A. Hawker Computers in Engineering COMP 208 Subroutines Michael A. Hawker Subprograms Functions are one type of subprogram in FORTRAN Another type of subprogram FORTRAN allows is called a subroutine There are many

More information

8 Piecewise Polynomial Interpolation

8 Piecewise Polynomial Interpolation Applied Math Notes by R. J. LeVeque 8 Piecewise Polynomial Interpolation 8. Pitfalls of high order interpolation Suppose we know the value of a function at several points on an interval and we wish to

More information

LECTURE 0: Introduction and Background

LECTURE 0: Introduction and Background 1 LECTURE 0: Introduction and Background September 10, 2012 1 Computational science The role of computational science has become increasingly significant during the last few decades. It has become the

More information

CS111: PROGRAMMING LANGUAGE II

CS111: PROGRAMMING LANGUAGE II 1 CS111: PROGRAMMING LANGUAGE II Computer Science Department Lecture 1: Introduction Lecture Contents 2 Course info Why programming?? Why Java?? Write once, run anywhere!! Java basics Input/output Variables

More information

A quick guide to Fortran

A quick guide to Fortran A quick guide to Fortran Sergiy Bubin Department of Physics Nazarbayev University History of Fortran One of the oldest general purpose high-level computer languages First developed in 1957 at IBM in the

More information

Introduction to Scientific Computing with Matlab

Introduction to Scientific Computing with Matlab Introduction to Scientific Computing with Matlab In the previous reading, we discussed the basics of vectors and matrices, including matrix addition and multiplication. In this class, we ll explore more

More information

Eng Marine Production Management. Introduction to Matlab

Eng Marine Production Management. Introduction to Matlab Eng. 4061 Marine Production Management Introduction to Matlab What is Matlab? Matlab is a commercial "Matrix Laboratory" package which operates as an interactive programming environment. Matlab is available

More information

NAGWare f95 and reliable, portable programming.

NAGWare f95 and reliable, portable programming. NAGWare f95 and reliable, portable programming. Malcolm Cohen The Numerical Algorithms Group Ltd., Oxford How to detect errors using NAGWare f95, and how to write portable, reliable programs. Support for

More information

PROBLEM SOLVING WITH FORTRAN 90

PROBLEM SOLVING WITH FORTRAN 90 David R. Brooks PROBLEM SOLVING WITH FORTRAN 90 FOR SCIENTISTS AND ENGINEERS Springer Contents Preface v 1.1 Overview for Instructors v 1.1.1 The Case for Fortran 90 vi 1.1.2 Structure of the Text vii

More information

Chapter 6. A Brief Introduction to Fortran David A. Padua

Chapter 6. A Brief Introduction to Fortran David A. Padua Chapter 6. A Brief Introduction to Fortran 90 1998 David A. Padua 1 of 15 6.1 Data Types and Kinds Data types Intrisic data types (INTEGER, REAL,LOGICAL) derived data types ( structures or records in other

More information

High Performance Computing and Programming, Lecture 3

High Performance Computing and Programming, Lecture 3 High Performance Computing and Programming, Lecture 3 Memory usage and some other things Ali Dorostkar Division of Scientific Computing, Department of Information Technology, Uppsala University, Sweden

More information

Optimising for the p690 memory system

Optimising for the p690 memory system Optimising for the p690 memory Introduction As with all performance optimisation it is important to understand what is limiting the performance of a code. The Power4 is a very powerful micro-processor

More information

CSE 262 Spring Scott B. Baden. Lecture 4 Data parallel programming

CSE 262 Spring Scott B. Baden. Lecture 4 Data parallel programming CSE 262 Spring 2007 Scott B. Baden Lecture 4 Data parallel programming Announcements Projects Project proposal - Weds 4/25 - extra class 4/17/07 Scott B. Baden/CSE 262/Spring 2007 2 Data Parallel Programming

More information

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and

CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims. Lecture 10: Asymptotic Complexity and CS/ENGRD 2110 Object-Oriented Programming and Data Structures Spring 2012 Thorsten Joachims Lecture 10: Asymptotic Complexity and What Makes a Good Algorithm? Suppose you have two possible algorithms or

More information

Information technology Programming languages Fortran Part 1: Base language

Information technology Programming languages Fortran Part 1: Base language INTERNATIONAL STANDARD ISO/IEC 1539-1:2010 TECHNICAL CORRIGENDUM 2 Published 2013-06-01 INTERNATIONAL ORGANIZATION FOR STANDARDIZATION МЕЖДУНАРОДНАЯ ОРГАНИЗАЦИЯ ПО СТАНДАРТИЗАЦИИ ORGANISATION INTERNATIONALE

More information

PACKAGE SPECIFICATION HSL 2013

PACKAGE SPECIFICATION HSL 2013 PACKAGE SPECIFICATION HSL 2013 1 SUMMARY Given a rank-one or rank-two allocatable array, reallocates the array to have a different size, and can copy all or part of the original array into the new array.

More information

The G3 F2PY for connecting Python to Fortran 90 programs

The G3 F2PY for connecting Python to Fortran 90 programs The G3 F2PY for connecting Python to Fortran 90 programs Pearu Peterson pearu@simula.no F2PY What is it? Example. What more it can do? What it cannot do? G3 F2PY The 3rd generation of F2PY. Aims and status.

More information

SUBPROGRAMS AND MODULES

SUBPROGRAMS AND MODULES SUBPROGRAMS AND MODULES FORTRAN PROGRAMING Zerihun Alemayehu AAiT.CED Program structure Advantages of subprograms Program units can be written and tested independently A program unit that has a well defined

More information

Introduction to Modern Fortran

Introduction to Modern Fortran Introduction to Modern Fortran p. 1/?? Introduction to Modern Fortran See next foil for copyright information Nick Maclaren nmm1@cam.ac.uk March 2014 Introduction to Modern Fortran p. 2/?? Acknowledgement

More information

Dr Richard Greenaway

Dr Richard Greenaway SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 2 Basic MATLAB Operation Dr Richard Greenaway 2 Basic MATLAB Operation 2.1 Overview 2.1.1 The Command Line In this Workshop you will learn how

More information

Modern Fortran OO Features

Modern Fortran OO Features Modern Fortran OO Features Salvatore Filippone School of Aerospace, Transport and Manufacturing, salvatore.filippone@cranfield.ac.uk IT4I, Ostrava, April 2016 S. Filippone (SATM) Modern Fortran OO Features

More information

Computer Programming

Computer Programming Computer Programming Dr. Deepak B Phatak Dr. Supratik Chakraborty Department of Computer Science and Engineering Session: Recap of Arrays and Simultaneous Equations (S31 S35) Dr. Deepak B. Phatak & Dr.

More information

A Brief Introduction to Fortran of 15

A Brief Introduction to Fortran of 15 A Brief Introduction to Fortran 90 1 of 15 Data Types and Kinds Data types Intrisic data types (INTEGER, REAL,LOGICAL) derived data types ( structures or records in other languages) kind parameter (or

More information

Math 226A Homework 4 Due Monday, December 11th

Math 226A Homework 4 Due Monday, December 11th Math 226A Homework 4 Due Monday, December 11th 1. (a) Show that the polynomial 2 n (T n+1 (x) T n 1 (x)), is the unique monic polynomial of degree n + 1 with roots at the Chebyshev points x k = cos ( )

More information

Basic Fortran Programming. National Computational Infrastructure

Basic Fortran Programming. National Computational Infrastructure Basic Fortran Programming National Computational Infrastructure Outline Introduction Declaration Arithmetic Do Loops Conditionals Functions I/O Libraries End 2 / 56 Fortran Programming Language Fortran

More information

Scientific Programming in C X. More features & Fortran interface

Scientific Programming in C X. More features & Fortran interface Scientific Programming in C X. More features & Fortran interface Susi Lehtola 20 November 2012 typedef typedefs are a way to make shorthand for data types, and possibly also make the code more general

More information

(Refer Slide Time 01:41 min)

(Refer Slide Time 01:41 min) Programming and Data Structure Dr. P.P.Chakraborty Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture # 03 C Programming - II We shall continue our study of

More information

MATLAB QUICK START TUTORIAL

MATLAB QUICK START TUTORIAL MATLAB QUICK START TUTORIAL This tutorial is a brief introduction to MATLAB which is considered one of the most powerful languages of technical computing. In the following sections, the basic knowledge

More information

Introduction to Matrix Operations in Matlab

Introduction to Matrix Operations in Matlab Introduction to Matrix Operations in Matlab Gerald W. Recktenwald Department of Mechanical Engineering Portland State University gerry@pdx.edu ME 350: Introduction to Matrix Operations in Matlab Overview

More information

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage: Discussion 1H Notes (Week 3, April 14) TA: Brian Choi (schoi@cs.ucla.edu) Section Webpage: http://www.cs.ucla.edu/~schoi/cs31 More on Arithmetic Expressions The following two are equivalent:! x = x + 5;

More information

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays

Maltepe University Computer Engineering Department. BİL 133 Algorithms and Programming. Chapter 8: Arrays Maltepe University Computer Engineering Department BİL 133 Algorithms and Programming Chapter 8: Arrays What is an Array? Scalar data types use a single memory cell to store a single value. For many problems

More information

Computational modeling

Computational modeling Computational modeling Lecture 5 : Monte Carlo Integration Physics: Integration The Monte Carlo method Programming: Subroutine Differences Subroutine/Function The Fortran random number subroutine Monte

More information

Fortran 90 - A thumbnail sketch

Fortran 90 - A thumbnail sketch Fortran 90 - A thumbnail sketch Michael Metcalf CERN, Geneva, Switzerland. Abstract The main new features of Fortran 90 are presented. Keywords Fortran 1 New features In this brief paper, we describe in

More information

Lecture 2 FORTRAN Basics. Lubna Ahmed

Lecture 2 FORTRAN Basics. Lubna Ahmed Lecture 2 FORTRAN Basics Lubna Ahmed 1 Fortran basics Data types Constants Variables Identifiers Arithmetic expression Intrinsic functions Input-output 2 Program layout PROGRAM program name IMPLICIT NONE

More information

2. Basic Elements of Fortran

2. Basic Elements of Fortran 2. Basic Elements of Fortran Structure of a Fortran Program 31 characters must be in the 1st line if present declaration section program my_first_program! Declare variables integer :: i, j, k! i, j, k

More information

Types II. Hwansoo Han

Types II. Hwansoo Han Types II Hwansoo Han Arrays Most common and important composite data types Homogeneous elements, unlike records Fortran77 requires element type be scalar Elements can be any type (Fortran90, etc.) A mapping

More information