62
ENGG1811 © UNSW, CRICOS Provider No: 00098G1 W8 slide 1 Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers

Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

  • Upload
    others

  • View
    24

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G1 W8 slide 1

Week 8

Numerical Computing with Matlab

w1 w4 w8 w11

SS BP NC IT

ENGG1811 Computing for Engineers

Page 2: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

Complexity of systems

• Computers are tools for modelling systems and

analysing data (among many other things)

• We’ve looked at very simple systems

– Data fits on a spreadsheet

– Algorithms don’t have to be very smart

• Optimisations problems have been simple too

– Solver-type with a few variables and linear equations

– Min/max type that we can solve iteratively

• Problem complexity ramps up in the real world

• Routing problems are challenges (saving fuel by

optimising delivery routes; loading schedules)

– Direct solutions are exponential in number of elements

– Only approximate solutions are practical

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 2

Page 3: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

A whole new level of complexity

• Human genome: 109 base pairs

– Analysis to identify patterns in genetic disorders

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 3

1014 ?? Neural connections

modelling, analysis of imaging data, understanding disorders like dementia, the nature of intelligence

Picture credit: National Geographic and http://www.engineeringchallenges.org/cms/8996/9109.aspx

Page 4: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

A complex world

• Need more and faster computers

• Need smarter algorithms

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 4

• Also need tools that allow you to test out different

algorithms quickly

– Rapid prototyping

• That’s how Matlab comes in

– Sometimes 10 lines of code in OO Basic can be done in 1 line in Matlab

• This week: Basic Matlab

• Later weeks: Algorithms, simulation, animation etc.

Page 5: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 5

Print Resources

Matlab is a powerful system with many features and a lot

of detail. Having access to a printed reference book is

likely to be useful, both for ENGG1811 and future courses.

These are recommended:

1.Chapman SJ (2012). MATLAB Programming with

Applications for Engineers, CENGAGE Learning.

2.Chapman SJ (2009). Essentials of MATLAB

Programming. CENGAGE Learning.

3.Pratap R (2009). Getting Started with MATLAB 8. OUP.

4.Moore H (2012). MATLAB for Engineers. Pearson.

1 (primary reference) and 3 are in the UNSW Bookshop.

The Library has few printed copies, but 2 is being partly

digitised.

Page 6: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

This Week’s References

• Chapman (2012):

– Chapter 1

– Chapter 2, sections 2.1 to 2.11

– Chapter 3, section 3.1 (more plotting)

• Chapman (2009):

– Chapter 1

– Chapter 2, sections 2.1 to 2.11

– Chapter 3, section 3.5 (more plotting)

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 6

Page 7: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 7

Online Resources

• Documentation at mathworks.com

http://www.mathworks.com.au/help/matlab/index.html

• Tutorials endorsed by MathWorks

http://www.mathworks.com.au/academia/student_center/tut

orials/launchpad.html

(the University of Edinburgh one is particularly good, these

links are on a page on the class website)

• Documentation that comes with Matlab.

help button

MATLAB® is a registered trade mark, but doesn’t warrant full

capitalisation as it’s not an acronym. It gets a single capital M in

these notes.

Page 8: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 8

What is numerical computing?

• Numerical computing environments (NCEs) model

systems described by mathematics, including cases where

– data is multidimensional, represented by vectors/arrays/matrices

– models use differential equations (ordinary and partial)

– models use complex variables

• NCEs can be used to analyse experimental data against

models, can provide approximate solutions to hard

problems and some can do symbolic manipulation

• NCEs are programmable, have built-in matrix operators,

2D and 3D plotting and many functions

• Spreadsheets can do some of this, but setting up models

can be tedious and error-prone

Page 9: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 9

Matlab

• Developed in the 1980s as a matrix laboratory

tool (logo shows the propagation of a disturbance

through an L-shaped membrane)

• Adopted throughout industry and the research

community as a standard tool (and in later courses)

• Current major release is 8 (2012b or later). Labs have

7.9 (2012a, Linux). Matlab is free for non-commercial

purposes while you are an UNSW student.

• Solutions are easily shared (but programming quality is

often very low, so difficult to understand and use)

• Non-commercial alternatives are, in order of compatibility

– GNU Octave (recommended, files are interchangeable)

– Scilab; FreeMat

Page 10: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 10

Matlab desktop

The Matlab desktop has four main windows

Select file

for editing

Ribbon, or menu + toolbars (depends on version)

Enter

commands

Review

previous

commands

View current

variables

Page 11: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 11

Matlab desktop, continued

• Other windows that appear when required are

– Documents window, where script and function files are edited, like the VBE

– Figure window, where the results of plot or other display commands are shown

– Path window, for specifying folders where you keep your Matlab files

– Help window

• Windows can be docked or undocked as you like

Page 12: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 12

Matlab as a calculator

• Matlab maintains a list of variables that can be modified

using assignment and other commands

– variables are not declared (no Dim equivalent)

– variables have no fixed type (no As … equivalent)

– variables must be assigned before use

– no constants but some predefined variables such as pi

• Types and structures include

– numeric (real or complex), actually a 1x1 complex matrix

– string (actually 1xN array of characters)

– array (vector or matrix)

– Literal strings are enclosed in single quotes, not double quotes as in OOB: 'Length of beam'

• Type commands into command window, results follow

• If too long, continue with ellipsis ..., like _ in OOB

Page 13: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8slide 13

Calculator mode, continued

• Up-arrow key copies last command for editing, ctrl-u clears

• Comments start with % (not single quote)

– intended for script files but legal in command window

• Variable assignment can be followed by a semicolon ; to

suppress result display

• Expression only: assigns to built-in variable ans

• Variable name only: show its value

• Command history shows what you’ve typed

• Current and previous min and max values shown in

workspace window

– workspace browser also used to examine arrays

• whos command shows variable summary

• clear command zaps the lot (or clear name)

Page 14: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 14

Example (area of ellipse)

>> % area of ellipse, generalisation of circle area % with major and minor semi-axes a, b >> a = 12 a = 12 >> b = 5.5; >> areaE = pi * a * b areaE = 207.3451 >> sqrt(3^2 + 4^2) ans = 5 >> caption = 'Area of ellipse'; >> whos Name Size Bytes Class Attributes a 1x1 8 double ans 1x1 8 double areaE 1x1 8 double b 1x1 8 double caption 1x15 30 char

Matlab’s response is

shown in italics in

these notes only

Page 15: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 15

M-files

• Matlab program code is stored in text files with a .m

extension, hence the name M-files

• An M-file can contain

– a script, a sequence of statements, or commands just like you would type in the command window, or

– a function, with the same name as the file without the .m

– a class definition, for specifying named constant values, and advanced programming techniques

• When you use an identifier at the beginning of a

command, Matlab looks

– in your variable workspace for a variable with that name

– in a series of folders known as the search path for a file with that name plus the .m

Page 16: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 16

Search path

• You can add folders or change the order using the Set

Path menu item

• In the labs the path includes the directory matlab in your

home directory

• To find out where Matlab locates an object, use which

• Never use a built-in name for any of your own objects

(variables, functions, filenames)

>> which areaE areaE is a variable. >> which sqrt built-in (C:\Program Files\MATLAB\R2012b\toolbox\

matlab\elfun\@double\sqrt) % double method >> which silly 'silly' not found.

Page 17: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

Organising Your Files

Matlab installation directory

toolbox

bin insert shortcut

Your working area (~/matlab in the labs)

en1811 files required for this course

demos complete lecture demos download

lectorig partial solutions

lectfinal complete solutions

testing where you experiment

labs where you complete lab work

assign2 where you complete the assignment

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 17

Page 18: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 18

Identifiers

• Matlab is case-sensitive, unlike OOB

• Names of variables, functions etc are generally in lower

case in textbooks and reference documentation, but

– camelCase for variables is still the ENGG1811 preferred standard

– vector and matrix variables are usually in lowercase such as v, a, m rather than the maths convention V, A, M etc

– lowercase for functions because of the filename connection

– abbreviations are generally OK, especially algebraic quantities.

– maxTemp is more common than maximumTemperature (say)

• To counteract the relatively reduced readability, a data

dictionary is required in ENGG1811 to explain purpose

of variables and functions (later)

Page 19: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 19

Fundamental types

• Matlab uses double precision for all numeric variables

– same as OpenOffice Calc, Microsoft Excel

• double values are complex numbers

– imaginary part, if any, is specified by appending i or j to

a number (j is an electrical engineering convention)

• Strings are 1xN arrays of char values (each 16bit,

representing full Unicode character set)

>> phase = 12 -5.3i % or 12 - 5.3i etc but not 12 – 5.3 i phase = 12.0000 - 5.3000i >> imag(phase) ans = -5.3000 >> real(phase) ans = 12

Page 20: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 20

Arrays

• Matlab stores data in arrays (even single variables)

– if the data has one dimension, it’s a vector

– if it has more than one dimension, it’s a matrix

– m x n means m rows and n columns

– scalar (single-valued) variables are 1x1

• Row vectors and column vectors are different:

5.12

8

23

123 45.3 0.4 1

Vcol

Vrow

Vrow is 1x4, Vcol is 3x1

Page 21: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 21

Array assignment

• Array literal data is enclosed in square brackets

– data is in row order

– rows separated by semicolons or end-of-line

– elements within a row separated by spaces or commas

commas preferred for expressions, complex (1-i and 1 –i differ)

– can drop the [ ] for 1x1 (fortunately)

>> vrow = [ 1 0.4 -3.45 123 ]; % row vector 1x4 >> vcol = [ 23; -8; 12.5]; % column vector 3x1 >> ident = [ 1 0 0; 0 1 0; 0 0 1]; % order 3 identity matrix >> m = [1, 4, 2.3, -7, 6; 0, 5i, 0, 1-2i, 1]; % 2x5

• Number of columns must be consistent

>> m1 = [1, 2, 3; 4, 5] Error using vertcat Dimensions of matrices being concatenated are not consistent.

Page 22: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 22

Accessing array elements

• Use round brackets with subscripts separated by commas

– row and column vectors use one subscript, matrices 2+

>> vrow(3) ans = -3.4500 >> vcol(1) = m(2,4) % replace element vcol = 1.0000 - 2.0000i -8.0000 12.5000

• Assigning to non-existent elements extends an array

>> vrow(7) = -1 % intervening elements become zero vrow = 1.0000 0.4000 -3.4500 123.0000 0 0

-1.0000

Page 23: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 23

Quiz

• What is vrow after running the following command?

>> vrow(3) = vrow(4)

>> vrow(7) = -1 % intervening elements become zero vrow = 1.0000 0.4000 -3.4500 123.0000 0 0

-1.0000

>> vrow vrow = 1.0000 0.4000 123.0000 123.0000 0 0

-1.0000

Page 24: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 24

Colon operator

• Colon operator generates all elements of an arithmetic

progression

first : increment : last

first : last (increment = 1)

• Extremely powerful when combined with array operators

(normal arithmetic operators but applied between a

scalar and an array, more later)

>> seq = 1:2:10 % odd integers less than or equal to 10 seq = 1 3 5 7 9

>> angles = (-1 : 0.01 : 1) * pi; % 201 values between

Page 25: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 25

Array functions

• Built-in functions that inform you about arrays

– length (elements in a vector or longest dimension of matrix)

– size (returns an array of all dimensions)

>> length(h) ans = 4 >> size(m) ans = 2 5 >>

• Matrix functions zeros, ones and eye (identity)

accept row and col sizes, or just one value if square

>> eye(length(seq)); % order 5 identity matrix (5x5)

>> zeros(size(m)); % 2x5 matrix filled with zeroes

Page 26: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 26

Subarrays

• Subscripts can themselves be arrays, result is an array of

just those elements

– special case, colon : stands for all subscripts in a dimension

– end symbolises the highest value of that subscript

>> arr1 = [1.1 -2.2 3.3 -4.4 5.5];

% arr1([1 4]) is [1.1 -4.4]

% arr1(1:2:5) is [1.1 3.3 5.5]

>> arr2 = [1 2 3; -2 -3 -4; 3 4 5];

>> arr2(:, 1:2:3) % all rows, but only first and third columns

ans =

1 3

-2 -4

3 5

>> arr1(3:end)

ans =

3.3000 -4.4000 5.5000

Page 27: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 27

• Subarrays can be assigned if either

– both sides have identical dimensions, or

– the right hand size is a scalar (copied to all elements)

>> flip = [1 2 3 4; 5 6 7 8; 9 10 11 12];

% the following copies the outer 4 elements to the 4 adjacent

% elements in the middle of the first two rows

>> flip(1:2,2:3) = flip(1:2:end, 1:3:end)

flip =

1 1 4 4

5 9 12 8

9 10 11 12

>> flip(3:end, 3:end) = -1 % last 2 elements on last row

flip =

1 1 4 4

5 9 12 8

9 10 -1 -1

Assigning subarrays

Page 28: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

Matrix indexing (1)

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 28

• m(3,5) = the element in row 3 and column 5

Row 3

Column 5

• m([1 3 5],5) = an array with 3 rows and 1 column

Rows 1, 3 and 5

Column 5

Note: comma here is the dimension separator (row vs column), not element separator

Page 29: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

Matrix indexing (2)

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 29

• m([1 3 5],[2 5]) = an array with 3 rows and 2 columns

Rows 1, 3 and 5

Columns 2 and 5

• [1 3 5] = 1:2:5

• m([1 3 5],[2 5]) is the same as m(1:2:5, [2 5])

m(:, [2 5]) is a sub-matrix containing the 2nd & 5th

columns of m

: means all

Page 30: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 30

H = 4 4 5 4 -8 -9 -4 6 5 0 -4 9 -6 -4 9 -9 -9 0 4 -3 -8 -1 -1 3 2 6 -2 3 -7 -6

Quiz

Hsub = H(2:3:6,[2 5 1])

What is the size of Hsub? 2 3

What are the elements of Hsub? -4 0 -9

-1 2 -8

Page 31: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 31

Special values

• Matlab predefines a few variables for use in calculations

– regrettably, they are not constants and can be assigned

– we’ve already used pi, i (or j) and ans

– three important ones are for testing calculation results

>> 123/0 % result is infinite (can be signed) ans = Inf >> 0/0 % result is undefined, not-a-number ans = NaN >> eps % minimum variation from 1.0 that can be stored ans = 2.2204e-16 >> pi = 3.6 % don’t try this at home folks pi = 3.6000

How to define and use genuine constants soon

Page 32: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 32

Formatting

• Default command window display format shows 4 digits

after the decimal point

– can change in Preferences, or use the format command

– format long g is a good alternative

– see Chapman 2.6.1 for full list

• The disp function constructs message from array of

strings (Chapman 2.6.2)

• For fine control (especially plot captions, later), use the

fprintf function

– first arg is template, % codes replaced by other args

– real values shown only. See doc for codes.

>> fprintf('pi is %.19g\ne is %15.9f\n', pi, exp(1)) pi is 3.1415926535897931 e is 2.718281828

Page 33: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 33

Reading data

• Simplest way to get input is directly from the user

– variable = input('prompt string');

• Array data can be read from a text file (*.dat)

– line structure reflects shape (row order)

– command is load name.dat

– data is assigned to array variable name

– csv files also supported but requires Excel to be installed

• can also save in ascii (*.dat) or M-file (*.m) format (the

latter has variable names)

>> temp = input('What is the current temperature (°C)? '); What is the current temperature (°C)? 23

>> fprintf('%g degrees Celsius is %g degrees Fahrenheit\n', ...

temp, convtemp(temp, 'C', 'F'));

23 degrees Celsius is 73.4 degrees Fahrenheit

Page 34: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 34

Operations

• Scalar operations as for OOB

– also left division \, but only useful for arrays

– precedence:

• parentheses

• exponentiation, left-to-right

• unary plus and minus

• multiplication and division, left-to-right

• addition and subtraction, left-to-right

Full list at:

http://www.mathworks.com.au/help/matlab/matlab_prog/operator-precedence.html

• Array and matrix operations are not the same!

– array ops are element-by-element, shapes must match

– array ops also OK with a scalar

– matrix ops use formal matrix arithmetic

Page 35: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

Matrix arithmetic (Semester 1 note)

• MATH1131/1141 may not quite have covered matrix

arithmetic yet, but will do so in the next week or so

• We won’t rely on this knowledge for a while, though

you do need to know that

– matrices are often used to store co-efficients for sets of linear equations

– there are special rules for multiplication, division, inverse and other operations

• Quick summary at

http://www.mathwarehouse.com/algebra/matrix/multiply-matrix.php

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 35

Page 36: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 36

Array and matrix operations

Operation Usage Applies to Meaning: (i,j) is any element

Addition a + b both element addition

Subtraction a - b both element subtraction

Multiplication

a .* b arrays element multiplication: a(i,j) * b(i,j)

a * b matrices matrix multiplication a b

Division

a ./ b arrays element division: a(i,j) / b(i,j)

a / b matrices = a * inv(b)

Left division

a .\ b arrays element division, reciprocal: b(i,j) / a(i,j)

a \ b matrices = inv(a) * b

Exponentiation a .^ b arrays element exponentiation: a(i,j) ^ b(i,j)

For arrays, a or b can be a scalar k. k*m is OK but k/m must be k./m

Page 37: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 37

Examples

• It’s easy to forget which operator to use

– Matlab is intended for matrix operations, so they are shorter

>> a = [1,2,3; 4,0,-2; 3,2,1];

>> b = [2,1,9; 1,-1,1; 1,2,3];

>> (a./b)*3 % divide elements, then scale ans = 1.5 6 1 12 0 -6 9 3 1

>> a/b % matrix division, warns if b is (nearly) singular ans = 0 0 1 -1.7333 4.4 3.0667 -1.0667 2.4 2.7333

>> a.\b % array left division, note middle diagonal value ans = 2 0.5 3 0.25 -Inf -0.5 0.33333 1 3

Page 38: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 38

Transpose operator (1)

• Transpose operator .' (single quote) can be applied as a

suffix to an array expression to exchange rows and

columns

• Important note:

.' is transpose

' is transpose and complex conjugate

>> g = [1 2+i]; % row vector >> h = g.' h = 1 2+i >> h = g' h = 1 2-i

Does not matter if your data is real. But be careful if you need to handle

complex numbers.

Page 39: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 39

Transpose operator (2)

• Quick way to produce column vectors without the ; row

separator notation

>> f = [1:4]'; % same as [1;2;3;4], also (1:4)' but not 1:4' >> g = 1:4; % row vector >> h = [g', g'] % Question: what does [g'; g'] give? h = 1 1 2 2 3 3 4 4

Page 40: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 40

Numeric functions

• Many useful functions are provided

– usual trigonometry, complex arithmetic, statistics

– Functions such as sin(), cos(), exp(), sqrt() etc. are

applied to each element in the array

>> t = [1 2 5 3]; % 4 elements

>> sin(t) ans = 0.8415 0.9093 -0.9589 0.1411

sin(t(1))

= sin(1)

sin(t(2))

= sin(2)

sin(t(3))

= sin(5) sin(t(4))

= sin(3)

Page 41: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 41

Built-in functions

• Many useful functions are provided (Chapman Table 2-8)

– usual trigonometry, complex arithmetic, statistics

– specialised functions for particular applications

– can return multiple results if relevant

– often accept and return arrays (‘mapping’ function)

>> t = 0:pi/6:pi; % 7 elements

>> sin(t).^2 ans = Columns 1 through 4 0 0.25 0.75 1 Columns 5 through 7 0.75 0.25 1.4998e-32

>> [biggest, pos] = max(sin(t).^2) biggest = 1 pos = 4 % column where biggest first occurs

note

rounding

error

Page 42: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 42

Plotting

• Major Matlab feature, far more sophisticated than

spreadsheet charts

– 2D and 3D

– data points represented by arrays for each dimension

– titles, annotations, styles easily added programmatically

– exportable in reusable or bitmap formats

>> t = 0:pi/100:50*pi;

>> plot(t, sin(t).*exp(-t/19));

>> grid('on'); % also grid on

>> title('Damped sine wave');

>> xlabel('\it{t}');

>> legend('sin(t) * exp(-t/19)', ...

'-exp(-t/19)'); optional LaTeX

equation code,

week 9

Page 43: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 43

Using M-files

• Command window is great for testing ideas, doing

simple calcs or showing very basic plots

– can save command history with the diary command

(Chapman 1.3.11)

• A worthwhile solution should be properly designed,

documented and saved

– script M-files record the solution structure, plus descriptive comments

– function M-files define sub-tasks that are potentially reusable

– class M-files are used in ENGG1811 for constants

• All can be created and edited by the Document editor,

which highlights language elements for clarity and does

simple validation checks

– Octave uses external editor such as NotePad++

Page 44: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 44

Scripts

• Scripts are programs storing sequences of statements

(commands)

• New script button (V8+) or menu File - New (labs V7)

– editor is tabbed, can have multiple files open

– Save As uses current folder by default

– file name is important, as that’s how you run the script

• ENGG1811: newscript('myscript'); or just newscript

– creates myscript.m in current folder

– template for required documentation is scrtemplate.m

you can carefully edit this to add your name etc

follows appropriate document standards for publishing

%% comment introduces new section in the file

Page 45: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 45

Documentation

• First line should be short descriptive title

– this line appears in window below file explorer, and is the

document title when published, so is better than the name

of the script file (Chapman’s preference)

• Then purpose in multiple comment lines (no space)

• Then change log and references

– shows authorship and history of major modifications

– references are necessary unless trivial or standard

• Then data dictionary

– list of variables used and how (= OOB decl. comments)

• Then problem parameter assignments if applicable

• Then code, divided into logical sections

– each has block comment, see Publish standards over

Page 46: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 46

Publish – layout rules

• Publish tab in editor and Publish button

– creates HTML doc (in html subfolder)

– help web browser reads these

– option to execute script and interpolate results including plots, for non-interactive scripts

• Sections are introduced by %%

– if there’s a title on the same line, is indexed

– if immediately followed by ordinary % comments, these

are formatted as a continuous, non-code paragraph

– optional empty line, then code (including block comments)

• Supports equations (LaTeX format, next week), bullet

and numbered lists, hyperlinks

– for full details search for publishing markup in the Matlab documentation center

Page 47: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 47

Example – horizon distance*

• Pythagorean theorem gives formula

for horizon distance d in terms of

height above the surface h and the

Earth’s mean radius R = 6371 km

* Based on Moore, Example 4.2

Rhhd

dRhR

2

)(

2

222

• The cliffs and headlands in the eastern

suburbs of Sydney are mostly about 40m

above sea level, so how far out to sea can

you see (use Matlab)?

Page 48: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 48

Solution development

Solutions will be more reliable and understandable if you

follow some common-sense steps

1. Describe the problem

find the distance to the horizon (km) at various heights (m)

2. Plan required inputs and desired outputs

inputs are a range of equally-spaced heights, via input()

output is a table (could be extended to other formats)

3. Decide what algorithm to use, do a hand calculation

analysis on previous slide, but rescale to km

4. Express solution as pseudocode (but Matlab-like)

5. Refine to Matlab steps (and later, functions), document

as you go

6. Test components of the solution where possible, and the

end-to-end product, revise

Page 49: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 49

Pseudocode

• Main steps:

– Inputs are the height limit and increment

– Construct vector of heights h

– Apply the algorithm to obtain vector of distances d in km

– Re-assemble vectors in tabular form and display

obtain maximum height from user, assign to htMax

obtain height increment from user, assign to htIncr

create height vector h using colon operator

apply horizon formula to h to produce vector d

create array T from d and h (row vectors => columns of T)

display T

Page 50: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 50

Constants

• Where do we get the Earth’s radius from?

– It's not really a variable like htMax or d, but R = 6371; looks

like it might be; try to avoid literals like this in scripts

– Matlab only provides a few (non-)constants, and no Const

– We have defined a bunch of them in a special M-file called a

class definition: NC (Named Constants), file is en1811/NC.m

– Four fundamental mathematical values: pi, e, gamma, phi

– Lots of universal physical ones like c, Boltzmann's constant

k, gas constant R and mass of the electron me

– Some astro constants, including Earth’s RE and ME

– Use any of them with the notation NC.name

– You can add to it if you like, but follow existing patterns

– Try these

commands:

>> NC.e % constant value

>> NC % lists all values

>> help NC % summary, click showdemo NC

Page 51: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

The important bits so far

• You can use Matlab as a calculator

• Has vectors [1, 9, 3.3] and matrices [2,-3; 0,4; 6.2,5]

• Matrix ops a*b, a/b different from array ops a.*b, a./b

• Scalars are OK, pi*m or pi.*m, m.^2

• Colon operator 0:0.01:2*pi especially good for plotting

• m(row,col), subscripts can be end or : (same as 1:end)

• plot(xvec, yvec), hold on for overlays

• disp variable or fprintf for fine control

• newscript name, template provided (use it!)

• must follow layout and documentation rules

• NC.constant (also PM.constant)

• Chapman text is worthwhile

• Octave with Notepad++ is a suitable free alternative

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 51

ENGG1811 Standards, installation needed

Page 52: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 52

Editing the script (Matlab program)

• Implementation follows, see final version in lecture code

package

• During editing, Matlab runs error checking continuously

– look for narrow coloured bars on RHS, hover to view

>> pwd % print working directory, where the file is created

ans =

C:\cygwin\home\en1811\Matlab\demos

>> newscript % ENGG1811 command, prompts if no name given

What is the name of the new script? horizon

Page 53: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 53

Running the program

• This exercise is quite short, so just test end-to-end

– in practice, functions can be tested independently and any problems corrected before the whole solution is assembled (like OOB functions in assign 1)

– improves debugging efficiency (see Chapman 2.15)

– compare 40m data point against hand calc, also zero

– can trace by setting breakpoints and stepping just like OOB

• Scripts use global workspace, intermediate values persist

• Program is not protected against silly inputs

– proper validation requires ifs (next week)

>> horizon % the name of the program

Largest height (m): 100

Height increment (m): 10

… % try it yourself

Page 54: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 54

More on plotting

• Many options to vary the type and appearance

plot(x, y) – plot with both linear scales

semilogx(x, y) – plot with x logarithmic scale, y linear

semilogy(x, y) – plot with x linear scale, y logarithmic

loglog(x, y) – plot with both logarithmic scales

plotfunc(x1, y1, x2, y2, …) – multiple plots for any of these

hold on – next plot overlays, also hold off, hold (= toggle)

axis([xMin, xMax, yMin, yMax]) – set axis limits

[xMin, xMax, yMin, yMax] = axis() – get axis limits

axis option – set axis shape (square, equal, normal, on, off)

figure(n) – plot on figure window n (>= 1)

subplot(m, n, sel) – divide current figure into m rows and n

columns, plot on selected number (single index, row order)

Page 55: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 55

Example – rates of diffusion*

• Metals are hardened by carburising, where carbon

diffuses into the heated metal at a rate D that depends

on the temperature T and material characteristics:

– R is the ideal gas constant (available as NC.R)

– diffusion coefficient D0 and activation energy Q depend on

the material

* Moore, Example 5.3, using SI units and including some corrections

RTQ

eDD

0

Material D0 ( m2/s) Q (J/mol)

Ferrite ( Fe) 6.2 x 10–7 80 000

Austentite ( Fe) 2.3 x 10–5 148 000

Page 56: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 56

Development steps

1. Problem – show diffusivity of C in two allotropes* of iron

2. Inputs/outputs

– apply formula from room temperature to 1200 °C, using constants from PM (Properties of Materials, includes the Fe diffusivity data)

– display results on plots of diffusivity against inverse temperature 1/T with different scale types

3. Algorithm and hand example

– formula provided, at 227 °C for gamma iron we get

4. Develop and refine solution (one step in this case)

>> 2.3e-5 * exp(-148000/(NC.R * (227+273.15)))

ans =

8.0392e-21 % Note: 1/(227+273.15) is 2.0 for checking

* See Wikipedia for a summary of the various forms of iron and their crystal structure

Page 57: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 57

Editing the script

Might as well call the script diffusion.m, but

so we’d better try a more specific name

>> newscript diffusion

Error using newedit (line 47)

cannot create diffusion.m as it already exists as

C:\Program Files\MATLAB\R2012b\toolbox\finance\finsupport\

@diffusion\diffusion.m

Error in newscript (line 33)

newedit(newFilename, 'scrtemplate.m');

>> newscript diffusionFe

Page 58: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 58

Initial version using only plot()

Page 59: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 59

Initial version using only plot()

Linear scales don’t show the relationship well enough.

See final version using subplot() in lecture code

package. Zoom in to check hand calc.

Page 60: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 60

Point spacing

• The colon operator is convenient, but

– sometimes what you want is a certain number of points, independent of the limits

– colon doesn’t guarantee to include the end point

– colon doesn’t work well for log scales (need a geometric progression rather than an arithmetic progression)

• linspace and logspace to the rescue

linspace(startValue, endValue, numPoints)

both limits are included if numPoints is at least 2

logspace(start10exp, end10exp, numPoints)

limits are the base-10 logarithm of the values (the power of 10 that the values represent)

Page 61: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 61

Point spacing

>> linspace(1,7,5) ans =

1 2.5 4 5.5 7

>> 261.626*logspace(0, log10(2), 13) ans =

Columns 1 through 5

261.63 277.18 293.67 311.13 329.63

Columns 6 through 10

349.23 370 392 415.31 440

Columns 11 through 13

466.16 493.88 523.25

The logspace result gives the frequencies in hertz of

the notes of the chromatic scale starting at middle-C

on the piano (defined such that A is exactly 440Hz)

Image source: Wikimedia

C A C’

Page 62: Week 8 Numerical Computing with Matlaben1811/15s1/lectures/week08.pdf · Week 8 Numerical Computing with Matlab w1 w4 w8 w11 SS BP NC IT ENGG1811 Computing for Engineers . Complexity

ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 62

Summary

• Matlab can be used as a scientific calculator with

built-in complex and matrix arithmetic and many

specialised functions for calculation and display

• use format, disp and fprintf for output control

• array notation: [ ], colon operator, indexing with :

and end, array vs matrix operators

• plotting with legend, title, labels, axes

• script structure, especially documentation standards

• Matlab path; running scripts

• plotting variations, semilog and loglog plots

• spacing data points