course: astm22 – computational astrophysics alexey bobrick...

26
Short introduction to MATLAB Course: ASTM22 – Computational Astrophysics Teachers: Alexey Bobrick – [email protected] David Hobbs – [email protected] MATLAB introduction lecture notes by: Daniel Carrera (doktorand) Alexey Bobrick Short MATLAB introduction slide 1 of 26

Upload: others

Post on 31-May-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Short introduction to MATLAB

Course: ASTM22 – Computational Astrophysics

Teachers:Alexey Bobrick – [email protected] Hobbs – [email protected]

MATLAB introduction lecture notes by:Daniel Carrera (doktorand)

Alexey Bobrick Short MATLAB introduction slide 1 of 26

Page 2: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Introduction to MATLAB

● Why MATLAB?● Lightning tour of MATLAB

– Variables and arrays– Conditionals– Loops– Functions– Importing data– Plots– Videos

● Machine precision– How computers store numbers– Arithmetic error– Implications for your programs

Alexey Bobrick Short MATLAB introduction slide 2 of 26

Page 3: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Why MATLAB?

Array-based programming language

1. The basic object is the array (e.g. vector, matrix).

2. Perform operations on entire arrays (e.g. vector addition, matrix product, QR factorization, etc).

3. Compact, clear code.

for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { C = A*B C[i,j] = 0; for (k = 0; k < q; k++) { C[i,j] += A[i,k]*B[k,j]; } }}

Alexey Bobrick Short MATLAB introduction slide 3 of 26

Page 4: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Why MATLAB?

Array-based programming language

1. The basic object is the array (e.g. vector, matrix).

2. Perform operations on entire arrays (e.g. vector addition, matrix product, QR factorization, etc).

3. Compact, clear code.

4. Good balance of performance and ease of use.

5. Array languages are a key tool in scientific computing.

Alexey Bobrick Short MATLAB introduction slide 4 of 26

Page 5: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

How to get MATLAB

MATLAB download for Lund University students:

http://program.ddg.lth.se/

Popular alternatives to MATLAB

- Octave http://www.gnu.org/software/octave/

Extremely similar language to MATLAB. Get the latestversion to get a GUI.

- Python + SciPyhttp://www.enthought.com/products/epd.php

General purpose programming language witha module for scientific computing.

Alexey Bobrick Short MATLAB introduction slide 5 of 26

Page 6: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Fancy calculator

>> 2 + 3 + 7 + 12 + 31 55

>> pi 3.1416

>> sqrt(2) >> help sqrt 1.4142

>> cos(2*pi) % Cosine uses radians. 1

>> (2+3i)^2 % Complex numbers. -5 + 12i

>> exp(123) 2.6195e+53

>> log(exp(123)) 123

Alexey Bobrick Short MATLAB introduction slide 6 of 26

Page 7: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Variables and arrays

>> a = 7 7

>> b = 2*a 14

>> u = [6 5 4 3 2] 6 5 4 3 2

>> u + [1 1 1 1 1] 7 6 5 4 3

>> u * 2 12 10 8 6 4

>> sqrt(u) 2.4495 2.2361 2.0000 1.7321 1.4142

Alexey Bobrick Short MATLAB introduction slide 7 of 26

Page 8: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Variables and arrays

>> uu = 6 5 4 3 2

>> max(u)ans = 6

>> min(u)ans = 2

>> sum(u)ans = 20

>> mean(u)ans = 4

>> length(u)ans = 5

Alexey Bobrick Short MATLAB introduction slide 8 of 26

Page 9: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Variables and arrays

>> A = [ 1 2 3 ; 4 5 6 ] % 2x3 Matrix.A =

1 2 3 4 5 6

>> size(A) % Matrix dimensions.ans =

2 3

>> uu = 6 5 4 3 2

>> size(u) % MATLAB sees 'u' as a 1x5 matrix.ans =

1 5

Alexey Bobrick Short MATLAB introduction slide 9 of 26

Page 10: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Variables and arrays

>> u' % Matrix transpose. 6 5 4 3 2

>> u' * u % Matrix product. 36 30 24 18 12 30 25 20 15 10 24 20 16 12 8 18 15 12 9 6 12 10 8 6 4

>> u .* u 36 25 16 9 4

>> u' .* uerror

Alexey Bobrick Short MATLAB introduction slide 10 of 26

Page 11: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Variables and arrays

>> A = rand(3) % Random matrix

0.573291 0.663319 0.265920 0.531253 0.481396 0.361992 0.203692 0.745661 0.053230

>> b = [1;2;3] % Column vector 1 2 3

>> x = A\b % Solve the linear system Ax = b -13.6425 6.5480 16.8387

Alexey Bobrick Short MATLAB introduction slide 11 of 26

Page 12: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Variables and arrays

a = [4 5 6]b = [7 8 6]

if a == b

disp(“Drive a car”)

elseif any(a >= b)

disp(“Take the bus”)

else

disp(“Take the train”)

end

if ( condition ) ...elseif ( condition ) ...else

Alexey Bobrick Short MATLAB introduction slide 12 of 26

Page 13: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Variables and arrays

for i = start:end ...end

while ( condition ) ...end

r = [];for i = 1:30 r(i) = i*iend

y = 100;while (y > 10) y = sqrt(y)*3end

Alexey Bobrick Short MATLAB introduction slide 13 of 26

Page 14: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Loops vs arrays

Rule #1: Aim to replace loops with array operations

Speed Loops are run by the MATLAB interpreter. Arrayops are done by the backend, written in C.

Clarity More often than not, your code will be moreconcise and clear.

Education MATLAB was designed around arrays. Learnanother way to approach programming.

Alexey Bobrick Short MATLAB introduction slide 14 of 26

Page 15: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Functions

Each function is stored in a separate file, the file name must match the function name.

File name: function_name.m

File contents:

function [output vals] = function_name(input vals)

... instructions ...

Alexey Bobrick Short MATLAB introduction slide 15 of 26

Page 16: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Functions

Example:

File name: lnorms.m

File contents:

%% Return the L1, L2 and L-infinity norms of a vector%

function [l1 l2 linf] = lnorms(vals)

l1 = sum( abs(vals) )l2 = sqrt( sum(vals .* vals) )linf = max( abs(vals) )

Alexey Bobrick Short MATLAB introduction slide 16 of 26

Page 17: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Importing data

Alexey Bobrick Short MATLAB introduction slide 17 of 26

Suppose you have a data file called:

data_file.dat

If it stores arranged numeric data, it can be imported by:

>> M = dlmread(data_file.dat)

… and the data will be saved into matrix M

dlmread automatically infers the format of the data in the file

Page 18: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Plots

Example:

Making a plot for arrays x,y: >> plot(x,y) %plot(x,y,'o') for different markers

Setting the options (after 'plot' command): xh=xlabel('x (m)'); yh=ylabel('internal energy (J/Kg)'); th=title('Internal energy vs distance'); %labels and title Axis([-0.4 0.4 1.8 2.6]) %plotrange: xmin,xmax,ymin,ymax set(gca,... 'linewidth',2,... %thickness of the line 'xcolor',[0,0,0],... %plot color 'fontsize',18,... 'fontname','arial'); %main plot style set([xh,yh,th],... 'fontweight','bold',... 'fontsize',18,... 'color',[0,0,0]); %plot label and title style

Alexey Bobrick Short MATLAB introduction slide 18 of 26

Page 19: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Plots

Example:

To make M-row N-column multi-panel plot:

>> subplot(M,N,plot number)>> … commands for making a plot of a given number>> subplot(M,N,next plot number)>> … commands for the next plot

>> pause(0.1) %Add if the plots are made in a loop

Alexey Bobrick Short MATLAB introduction slide 19 of 26

Page 20: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Videos

Alexey Bobrick Short MATLAB introduction slide 20 of 26

Example:

To make a video consisting of several plots:

vidObj = VideoWriter('peaks.avi');open(vidObj);Z = peaks; surf(Z); axis tightset(gca,'nextplot','replacechildren');for k = 1:20 surf(sin(2*pi*k/20)*Z,Z) currFrame = getframe; writeVideo(vidObj,currFrame);endclose(vidObj);

Page 21: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Machine precision

Single precision (32 bit)

1.b1b

2b

3b

4b

5b

6b

7b

8b

9…b

23

(or about 7 – 8 decimal digits of precision)0 = positive1 = negative e – 127

(goes from -127 to +128)

Largest value: ~ 2128 ≈ 3 x 1038

Alexey Bobrick Short MATLAB introduction slide 21 of 26

Page 22: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Machine precision

Alexey Bobrick Short MATLAB introduction slide 22 of 26

Double precision (64 bit)

1.b1b

2b

3b

4b

5b

6b

7b

8b

9…b

52

(or about ~17 decimal digits of precision)0 = positive1 = negative e – 1023

(goes from -1023 to +1024)

Largest value: ~ 21024 ≈ 10309

Page 23: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Machine precision

- Adding or subtracting very different numbers:

- Subtracting very similar numbers.

>> a = 1e18a = 1.0000e+18

>> b = 327b = 327

>> c = a + bc = 1.0000e+18

>> c - aans = 384

!!!

Alexey Bobrick Short MATLAB introduction slide 23 of 26

Page 24: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Machine precision

Some fractions cannot be represented in binary.

In decimal: 1/3 = 0.33333333333...1/10 = 0.1

In trinary: 1/3 = 0.1 In binary: 1/2 = 0.1

1/5 = 0.0011001100110011...1/10 = 0.0001100110011001...

Numbers like 0.1 and 0.2 cannot be represented exactly in binary.

Alexey Bobrick Short MATLAB introduction slide 24 of 26

Page 25: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Machine precision

Alexey Bobrick Short MATLAB introduction slide 25 of 26

MATLAB tries to do some magic to detect and correct these problems:

>> a = 0.2a = 0.20000

>> a = a + aa = 0.40000

>> a = a + a + 0.2a = 1

But that also means that you may have a nasty surprise when the magic fails...

Page 26: Course: ASTM22 – Computational Astrophysics Alexey Bobrick ...david/teaching/SPH/notes/MATLAB-Lecture.pdf · Lightning tour of MATLAB – Loops vs arrays Rule #1: Aim to replace

Lightning tour of MATLAB – Defensive programming

Make your code resilient to machine error.

% Suppose 'a' and 'b' are not integers.

if (a == b)

Option 1: if (a >= b)

Option 2: epsilon = 1e-5...if ( abs(a - b) < epsilon )

You have to make a judgement and decide which (if any) of these alternatives is appropriate.

Alexey Bobrick Short MATLAB introduction slide 26 of 26