YOU ARE DOWNLOADING DOCUMENT

Please tick the box to continue:

Transcript
Page 1: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Material

1.Grading sheet2.Micromanaged schedule3.Literature list4.Reading list and lecture content5.Matlab introduction exercises6.Project 1

Part 1: Air resistancePart 2: Planetary motionPart 3: Advanced exercises

7. Numerical methods lit. extracts8. Mechanics lit. extracts

Address to e-book linked at web site:

http://www.springerlink.com/content/w8302n/? p=35f7440cdc9b4ab6bc38d380d9b3c4aa&pi=0

Numeriska beräkningar i Naturvetenskap och Teknik

Page 2: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Part A, Technical aspects and the use of MATLAB 1. Short history. Why machine based computing?2. Programming3. Demonstration of basics

Part B, Numerical Methods

1. Numerical solution of differential equations2. Numerical solution of algebraic equations3. Fitting models to data 4. Adaptation to problem in physics: planetary motion

Numeriska beräkningar i Naturvetenskap och Teknik

Page 3: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Why compute using machines and numerical methods?

1. Work saving for extensive and trivial calculations

2. Reproducible results, minimizes errors due to the ”human factor”. However, new possibilities or mistakes arise: programming errors

3. Equation solving: including algebraic equations but

above all differential equations that lack solution in closed form, i.e. that have no analytical solution.

4. Monte Carlo simulations of stochastic processes Points 3 and 4 are the main reasons computers are vital in modern physics.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 4: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Wilhelm Shickard: 1592 – 1635 From Tuebingen, Germany. Designed mechanical calculator for

addition of six figure numbers. Some issues remain unclear. Limited future influence. Reconstructed.

Numeriska beräkningar i Naturvetenskap och Teknik

1623

Page 5: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

1670

Numeriska beräkningar i Naturvetenskap och Teknik

Blaise Pascal: 1623-1662Invented the so called ”Pascaline” around 1645. The purpose was to simplify his father’s work as tax collector in Rouen, France. The machine could add and multiply. Subtractions was complicated and time consuming.

1645

Page 6: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Gottfried Leibniz: 1646-1716

Constructed in 1670 the first machine that could do all the four basic algebraic operations.

1670

Numeriska beräkningar i Naturvetenskap och Teknik

Page 7: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Charles Xavier Thomas de Colmar: 1785-1870.

Based on Leibniz design de Colmar constructs the first commercially successful mechanical calculator, the arithometer.Ca 1500 are made for use by the French civil service.

1670

1820

Numeriska beräkningar i Naturvetenskap och Teknik

Page 8: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Charles Babbage: 1791-1871

Designed the first programmable calculator (difference engine) with the purpose to reduce the number of errors in mathematical tables. Later designed a mechanical computer, the analytical engine.Neither machine finished during hislifetime.

Ada Countess of Lovelace:

Known as the first programmer.Wrote program to calculate the so-called Bernoulli numbers using Babbages analytical engine.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 9: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Georg and Edvard Scheutz: 1785-1873and 1821-1881

Numeriska beräkningar i Naturvetenskap och Teknik

Page 10: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Alan Turing: 1912-1954

Computer science pioneer. Formalized the algorithm concept and introduced, in 1936, the theoretical background of computers with the ”Turing machine”, defined by a set of instructions, storage space etc. Today a machine of this kind iscalled a finite-state machine.

Konrad Zuse: 1910-1995

Constructed in 1941 the first programmable computer based on telephone relays partly financed by ”Deutsche Versuchsanstalt fur Luftfarth”.

1936

Numeriska beräkningar i Naturvetenskap och Teknik

Page 11: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

John von Neumann: 1903-1957

Born in Budapest. PhD in math and chemicalengineer

Immigrated to the US and became citizen in 1938

One of the first faculty members at IAS, Princeton together with Einstein, Gödel, Weyl.

Made significant contributions in

- Mathematics - Physics- Economic theory- Computer science etc…

Original work on computing at Princeton in relation to ballistic calculations, latersimulations for thermonuclear explosions.

Numeriska beräkningar i Naturvetenskap och Teknik

Johnny vNMorgenstern

Page 12: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

John von Neumann: 1903-1957

Wrote, in 1945, ”The first draft report on the EDVAC”EDVAC (Electronic Discrete Variable Automatic Computer) was the successor of ENIAC (the Electronic Numerical Integrator and Calculator) which in turn was the first large scale programmable digital computer (vacuum tube based).

EDVAC, in contrast to ENIAC, could be reprogrammed without physical recabling as the program and data were in memory. This kind of machine, which stores program and data in the same memory unit is the dominating computerarchitecture today and goes under the name ”von Neumann architecture”.

Numeriska beräkningar i Naturvetenskap och Teknik

Oppie

Feynman

Ulam

CU

ALUIN OUT

MEM

CPU

Page 13: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

SOME BASIC CONCEPTS

Numeriska beräkningar i Naturvetenskap och Teknik

Page 14: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

CPU and instruction set

Every instruction that the processor (CPU) can execute corresponds to a code, i.e. a number stored electronically in the memory of the machine.

-------------------------------------------------------------

Typical instructions contain a so-called opcode that corresponds to a command, and one or several operands that the opcode uses as arguments.

-------------------------------------------------------------

All instructions are operations on binary numbers in the computer memory.

-------------------------------------------------------------

A processor has a limited number of instructions it can perform. These make up the processors’ instruction set.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 15: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

A typical sequence to add two numbers, a and b, could be based on instructions such as Load and Add etc:

1. Load a in register 1 in memory

2. Load b in register 2 in memory

3. Add register 1 to register 2

4. Store register 2 in the position of b in memory

This means that programming became a complex problem in itself.

Using machine code is both time consuming and prone to programming errors.

------------------------------------------------------------

Still, this was the way the first computers were programmed and it is still in use under certain circumstances.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 16: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Low level and high level programming

In low level programming one uses a programming language which is close to the instruction set of the processor.

One such method goes under the name assembler programming.

--------------------------------------------------------------

In this case instructions such as addition, subtraction, bit shifts, register access etc are coded using mnemonics.

These are translated by a program to the numbers that correspond to a certain instruction in the set, i.e. to machine code.

--------------------------------------------------------------

Mnemonics can e.g be:

DEC B, (decrease content of register B), ADD A,B (add reg A to reg B) etc.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 17: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Low level and high level programming

For the most part modern programmering is done in high level programming languages whose syntaxes are such that they are close to our ordinary language. Several high level languages have been developed over the years. Some well known ones are:

FORTRAN (Formula translation)

COBOL (Common business language)

ADA (in honor of Lady Lovelace)

LISP (List processing language)

PASCAL (in honor of Blaise P),

C (it developped from B…)

SIMULA (a commonly used training language, weird…)

C++ (Object oriented ’extension’ of C)

--------------------------------------------------------------

All these contain similar structures but have slightly different syntaxes.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 18: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Interpreted and compiled programming languages

Source code

Machine code

Machine code

CompilerInterpreter

Performed once

Produces an executable file

Performed every time program runs

BASIC, different scripting languages (Perl, Ruby)

FORTRAN, C, C++

Produces executable code line-by-line

Rel. slow

Quick

Java: byte code compiler + Virtual machine -> machine code => Portability (compile once run everywhere)

MATLAB

Numeriska beräkningar i Naturvetenskap och Teknik

Page 19: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

MATLAB as calculator:

>> 2 * 2

ans = 4

>> ans*2

ans =8

The latest answer stored in ans

>> pi

ans = 3.14159265358793

Command window i MATLAB

Numeriska beräkningar i Naturvetenskap och Teknik

Page 20: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Variable

Entity introduced in order to store numerical values

In classical physics it can be time, acceleration, position etc...

--------------------------------------------------------

It is a very GOOD idea to give names to variables that

connect to their use.

--------------------------------------------------------

For physics problems, it is good to use notation given by the standard physics notation for the quantity.

This is very helpful when programming under all circumstances.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 21: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Look at the trivial example

>> A=1A = 1

>> B=2B = 2

>> C=A*BC = 2

Numeriska beräkningar i Naturvetenskap och Teknik

Page 22: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Och jämför med:

>> m=1m = 1

>> a=2a = 2

>> F=m*aF = 2

>>

Numeriska beräkningar i Naturvetenskap och Teknik

Page 23: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Variables

Variables can be of different types. Depending on type the computer will store the variable using a different number of bits.

----------------------------------------------------------

Types can be:

1. Integers of different lengths, 8, 16, 32, 64 bits etc

2. Floating point numbers of different lengths, i.e. decimal numbers with different precision

3. Vectors/matrices

4. Strings

etc...

----------------------------------------------------------

Normally such a program begins with a declaration sequence.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 24: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Variables

In MATLAB which, like BASIC, is an interpreted language one does not have to declare the type of the variable (integer, float, string etc), the interpreter decides about the type from the assignment:

>> A=1.234

A =

1.2340

A is a decimal number (a floting point number or a float)

Numeriska beräkningar i Naturvetenskap och Teknik

Page 25: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Variables

>> b=[1;2;3]

b = 1 2 3

b is a vector

>> B= [1 2 3; 4 5 6;7 8 9]

B= 1 2 3

4 5 6

7 8 9

B is a matrix

Matrices can have more than two dimensions

Numeriska beräkningar i Naturvetenskap och Teknik

Page 26: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Variables

One can also write

>> b(1)=1b =1

>>b(2) =2b=1 2

>>b(3) =3 b=1 2 3

Good in programs…

Numeriska beräkningar i Naturvetenskap och Teknik

Page 27: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Variables

In the same way

>> A(1,1)=1

A = 1

>> A(1,2) = 2

A = 1 2

>>A(2,1) = 3

A = 1 2 3 0

>>A(2,2) = 4

A = 1 2 3 4

Add index for more dimensions.

One can add matrices to matrices…

and matrices to matrices of higher dimension…

Numeriska beräkningar i Naturvetenskap och Teknik

Page 28: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Special vectors

>>a=1:10ans=

1 2 3 4 5 6 7 8 9 10>>a=0:0.1:1ans=

0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9

Other: linspace(a,b) one hundred evenly distributed elements between a and blinspace(a,b,n) n elements between a and b

Delvektorer: x(i), element ix(i:j) sub vector of elements i till jx(i:k:j) sub vector of elements i to j at step kx([i1 .... ip]) sub vector of given elements

Numeriska beräkningar i Naturvetenskap och Teknik

Page 29: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Special matrices

zeros(n) nxn zero matris

zeros(n, o, p...) n x o x p zero matris

ones(...) in the same way a matrix with ones

eye(..) unity matrix, one on the diagonal

rand(..) n x n random matrix, 0 to 1

randn(..) normal distribution of random elements

In a compiled language the size is often given in the declaration

Numeriska beräkningar i Naturvetenskap och Teknik

Page 30: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Precision

The internal precision in a MATLAB calculation is given by the fact that numbers are stored as ”doubles”.

In a 32 bit machine a double is stored as:

sign + exponent + mantissa in 64 bits

Which gives approximately 16 figures precision.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 31: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Assignments

Note that an assignment is not the same as an equation!

>>x = 1

x=1

>>x = x +1

x=2

i.e. to the value in the memory position of x (=1)

1 is added giving the result 2.

>>workspace -> gives a list of all variables

Numeriska beräkningar i Naturvetenskap och Teknik

Page 32: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Two results that may indicate a failed calculation

Inf (Infinity)

>>a=2

a=2

>>a/0 built in ‘exception handler’

ans = inf

NaN (Not a Number)

>> 0/0

ans = NaN

Numeriska beräkningar i Naturvetenskap och Teknik

Page 33: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Assignments & operators:

The standard operators can be used as expected:

addition +

subtraction -

multiplication *

division /

exponent ^

---------------------------------------------------------

Same order of priority as usual

>>a=2*3-1*2

a=4

>>a=2*(3-1)*2

a=8

Numeriska beräkningar i Naturvetenskap och Teknik

Page 34: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Assignments & operators

A matrix multiplied by a scalar:

>>A=[1 2 3; 1 2 3; 1 2 3];

>>c = 2;

>>B=c*A

B=

2 4 6

2 4 6

2 4 6

but…

Numeriska beräkningar i Naturvetenskap och Teknik

Page 35: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Assignments & operators:

Elementwise multiplication with .*

>> A.*B

2 8 18

2 8 18

2 8 18

Similarly elementwise division ./

Numeriska beräkningar i Naturvetenskap och Teknik

Page 36: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Assignments & operators:

Usual matrix multiplication, number of rows of A equal to the nr of columns in B:

>> A*B

12 24 36

12 24 36

12 24 36

Other functions:

Transpose: A’

Inverse: inv(A)

Determinant: det(A)

Numeriska beräkningar i Naturvetenskap och Teknik

Page 37: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Assignment & operators

Scalar and vector products:

>>a = [1 2 3];

>>b = [1 2 3];

>>c = dot(a,b)

ans =

14

>>cross(a,b)

ans =

0

Numeriska beräkningar i Naturvetenskap och Teknik

Page 38: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Why programs?

1.Problems that require repeated calculations with

different input data for a new set of output data

2. Complicated problems solved by complicated computations

e.g. differential or integral equations

3. Today also vital for control systems often defined as

finite state machines: airplanes, cars, workshop and

production machinery

Numeriska beräkningar i Naturvetenskap och Teknik

Page 39: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

To think about before and while you program

1. Define the general problem

2. Look for the structure of the problem and divide it into sub problems

3. Select method

4. Analyze input and output data. What goes into the pgm and what comes out?

5. If necessary make flow chart

6. Debug while writing. Never write from A to Z and expect it to work.

7. Document continuously, use comments in the program as well as notes

Numeriska beräkningar i Naturvetenskap och Teknik

Page 40: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Errors mainly of two types:

1. Syntax errors

Typos (mis-spellings of commands), misunderstanding syntax or limited knowledge of syntax.

These errors are discovered by the compiler and an error message is given. An experienced programmer learn which mistakes correspond to a certain error message and solves such a problem quickly.---------------------------------------------------------2. Run time errors

Design error in the program. Can lead to an incorrect resultat but also to ”program crash”. Often caused by a limited analysis of how a complete set of input data is processed in a program algorithm. “Dangerous error”.

Solution, write short pieces of code before testing and debug often!

Numeriska beräkningar i Naturvetenskap och Teknik

Page 41: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Building blocks

1. Statement sequences Simple statements, e.g. assignments that follow each other

2. Alternative flow paths

Depending on a specific condition different statements are executed. E.g. if the requested precision has been reached the calculation is ended and the result presented.

3. Repetitions

A task is performed several times until a condition is fulfilled. As an example: when 10 terms are required for a given series expansion

Numeriska beräkningar i Naturvetenskap och Teknik

Page 42: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

How to define a condition?

Numeriska beräkningar i Naturvetenskap och Teknik

Page 43: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Logical expressions:

Expressions with an answer of type true or false, represented by 1 or 0

a=1;b=2, a==b false,

&, |, ~

<

<=

==

>=

~= (not equal to)

MATLAB specific

any(arg) any element =

all(arg) all elements =

Numeriska beräkningar i Naturvetenskap och Teknik

Page 44: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Flow paths

If-statements

if logical expression if a~=1 statements disp(a)endif end

Can be expanded with else:

if logical expression if a==1statements disp(a)

else else satsgrupper disp(b) endif end

Numeriska beräkningar i Naturvetenskap och Teknik

Page 45: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Alt.

If logical expression statement elseif logical expression statement elseif logical expression statement

....else

statement end

Numeriska beräkningar i Naturvetenskap och Teknik

Page 46: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Switch statements

switch variable switch acase value1 case {1}

statements disp (a) case value2 case {7} statements b=input(’give b’)

.... case value3 case {11.7} statements c=23

otherwise otherwise statements a=a+23 end end

Numeriska beräkningar i Naturvetenskap och Teknik

Page 47: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

For loop:

for variabel = a:h:b for a=0:0.1:10

statements b=b+a end end----------------------------------------------------While loop:

while logiskt uttryck while a<b

statements a=a+0.1

end end----------------------------------------------------Loops can be written inside other loops resulting in nested loops...

Error(teckensträng), pause, break kan be use for flow control

Numeriska beräkningar i Naturvetenskap och Teknik

Page 48: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Error(tstring)

exits m-file and writes string

pause

waits for key press

Break

can be used for flow control, exits the while or for loop the program was executing.

Numeriska beräkningar i Naturvetenskap och Teknik

Page 49: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Functions

When all sub problems have been defined for the program it is often natural to perform some tasks using calls to the same code sequence from a main program. This is the reason for writing functions.

Definition:

Function [utvar1, utvar2, utvar…] = filnamn(invar1, invar2, invar…)%comments

Exemple of function call

[b1, b2, b3….] = filnamn(a1, a2,a3….)

Numeriska beräkningar i Naturvetenskap och Teknik

Page 50: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Global variables:

The variables in a function are normally local, i.e. they are set to 0 when program leaves the function.

One can define variables to be accessible outside of the routine to avoid zeroing them by giving the definition:

global var1 var2 …

MAINglobal x

f1global x y z t s f2

global x y z t

f3q t r s

Numeriska beräkningar i Naturvetenskap och Teknik

Page 51: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Input data to a program and output data from a program constitutes so-called i/o

INPUT DATA

1. The user gives input data to the program by answering questions put by the program

2. Hard coding, in data given in the program as assignments

3. In data read from file

OUT DATA

1. Written to screen (terminal output)

2. Written to file

Numeriska beräkningar i Naturvetenskap och Teknik

Page 52: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Input/Output

>> svar = input(‘give input value:’)

give input value:10

svar=

10

>>svar=input(‘give input value:’)

give input value:’abc’

svar=

abc

Write to screen with disp

>>disp(svar)

abc

Numeriska beräkningar i Naturvetenskap och Teknik

Page 53: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

M-filer

In MATLAB one may write programs or scripts in so-called m-files using a built in editor a debug utility.

For larger programs functions are often put in separate m-files. Open the editor by

>>edit

Numeriska beräkningar i Naturvetenskap och Teknik

Page 54: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

DEMO

Calculate arctan(x) using the series:

1||),(753

)arctan( 9753

xxOxxx

xx

0iia

12)1(

)12(

i

xa

ii

i

Numeriska beräkningar i Naturvetenskap och Teknik

Page 55: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Read/Write to/from files

1. Save workspace

save myfile saves all variables in myfile.mat

load myfile.mat reads all variables from myfile

alt.

save myfile a b c saves the variables a, b, c

2. Formatted reading and writing

fp= fopen(namn,’r’), opens file for reading

fp= fopen(‘namn’,’w’), opens file for writing

Numeriska beräkningar i Naturvetenskap och Teknik

Page 56: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Read/write to from files

Close file: fclose(fp)

------------------------------------------------------

Read from file: A=fscanf(fp,formatcode, dim)

dim = n, read n elements to A as column vector

dim = inf, read all numbers in the file to A as column vector dim = [m,n], m x n element to A as m x n matrix

------------------------------------------------------

write to file:

A=fprintf(fp,formatkod, A, dim)

Format codes

%e, %E exponent form with small/large e

%f, decimal form, %u integer, %s string,

\n ny rad

Numeriska beräkningar i Naturvetenskap och Teknik

Page 57: Material 1.Grading sheet 2.Micromanaged schedule 3.Literature list 4.Reading list and lecture content 5.Matlab introduction exercises 6.Project 1 Part.

Input/Output

Mer sofistikerad utskrift:

fprintf(formatkod,x)

Format codes:

%a.bf decimal form, a figures with b decimal figures, right justified

%a.be exponent, small e

%a.bE exponent, large E

%u heltal

>>a = 1.1234;

>>fprintf(‘the number is %4.2f’,a)

The number is 1.23

Numeriska beräkningar i Naturvetenskap och Teknik


Related Documents