Post on 11-Jul-2018
ENGG1811 © UNSW, CRICOS Provider No: 00098G1 W8 slide 1
Week 7 Numerical Computing with Matlab
ENGG1811 Computing for Engineers
What you have done by now
• OpenOffice Calc – Limitations: small scale problems, limited
functionalities
• OpenOffice Basic – Powerful programming constructs
• Assignment, if-then-else, for and while loops, functions
– Need to develop a lot of functions from scratch yourselves
– Limited to small-scale problems
• Complexity is a real issue for modern day engineering and science problems
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 2
Complexity in engineering and science
• An Intel i7 microprocessor has 731 million transistors
• More than 1 billion computers in the Internet
• Boeing 787 was designed using 800,000 hours of computing time on Clay supercomputers
• Faster computers are only a part of the solution
• We also need smarter algorithms!
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 3
Smarter algorithms
• Sequencing the genes
• Straightforward method: Read from one end to the other end
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 4
CTGAGTAGATACAATCAGAATTGA…
• Shotgun method – Make many copies of the genes. Bacteria can do this! – An illustration of the algorithm with 2 copies and small
fragments but in reality, many copies and longer fragments
ATACACAT
ATACACAT
ACAT ATAC
ATACA CAT
Puzzle
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 5
ACTAG ACT
TAG
AGA
ATAG
• Is it possible to determine what the original sequence is given the fragments?
• Computers and algorithms provide an entirely new solution!
Another level of complexity
• Human genome: 109 base pairs
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 6
1014 ?? connections
Picture credit: National Geographic and http://www.engineeringchallenges.org/cms/8996/9109.aspx
A complex world
• Need more and faster computers
• Need smarter algorithms
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 7
• 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.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 8
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. Some examples are:
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.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 9
Online/offline 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/tutorials/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. Accessible with the help button
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
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 OO Basic editor – 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
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
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)
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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 15
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)
• Good software engineering practice should be applied: define constants, explain purpose of variables and functions
Organising Your Files
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 16
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 17
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 (will explain this later)
First m-file
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 18
Save this file in CalcRopeRadius.m (File extension added by Matlab automatically) Type CaclRopeRadius in the command window to run the script
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 19
Fundamental types
• By default, Matlab uses double precision for all numeric variables, however there are other data types too
• 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.3 * i phase = 12.0000 -‐ 5.3000i >> imag(phase) ans = -‐5.3000 >> real(phase) ans = 12
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 two dimensions, it’s a matrix – m x n means m rows and n columns – scalar (single-valued) variables are 1x1 – Higher dimension (> 2) arrays are possible
1x4 array
3x2 array
Plotting experimental data (1) • Motivation: Understanding car vibration
• Shake the car at various frequencies – Low frequency: slow shaking – High frequency: fast shaking
• Wants to know how much the car body vibrates
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 21
http://johndayautomotivelectronics.com/wp-content/uploads/2013/04/dSPACE_4-30-13-PressRelease_Bild_ASM-KnC_RGB.jpg http://www.emercedesbenz.com/Images/Jan07/09_Mercedes_Testing_The_2008_C_Class/110083006c4004_04.jpg
Plotting experimental data (2)
• You shook the car at 5 different frequencies and observed the amplitude of vibration
• You want to plot a graph of amplitude against frequency
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 22
Frequency Amplitude 0.10 0.2 0.25 0.3 0.50 0.4 0.75 0.4 1.00 0.25
>> % Use an array to store the frequencies >> frequency = [0.1 0.25 0.5 0.75 1]; >> % Use another array to store the amplitudes >> amplitude = [0.2 0.3 0.4 0.4 0.25]; >> % plot amplitude against frequency >> % i.e. amplitude in y-‐axis and frequency in x-‐axis >> plot(frequency,amplitude) >> % More features on plotting will be explained later
Entering arrays
• Rules for entering arrays – Enter one row at a time, starting from the first row
– 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)
Row 1
Then, Row 2
Then, Row 3
Array assignment
• Array literal data is enclosed in square brackets
• Examples:
>> 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]; % 5x2
• Row vectors and column vectors are different:
[ ]
⎥⎥⎥
⎦
⎤
⎢⎢⎢
⎣
⎡
−=
−=
5.128
23123 45.3 0.4 1
Vcol
Vrow vrow is 1x4
vcol is 3x1
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 25
Array assignment (cont’d)
• Number of columns must be consistent
>> m1 = [1, 2, 3; 4, 5] Error using vertcat Dimensions of matrices being concatenated are not consistent.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 26
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 >> % m(2,4) – element at row 2, column 4 >> 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 27
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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 28
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(h)); % 4x4 identity matrix >> zeros(size(m)); % 2x5 matrix filled with zeroes
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 29
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 ± π
Quiz
• If you want to generate 50 equally spaced numbers such that first one is 0 and the last one is 100, how can you use the : operator to realize that?
• Can you use ?
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 30
>> 0 : 100/49 : 100
>> linspace(0,100,50)
1st number Last number Number of elements in the array
• Your work: Look up what logspace does.
>> 0 : 2 : 100
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 31
Built-in functions (1)
• 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]; % 7 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)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 32
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)); >> grid('on'); % also grid on >> title(’Sine wave'); >> xlabel(’t');
Code: plot_sine.m
Importing data for plotting
• Measurements may be stored in files
• They can be imported into Matlab for plotting
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 33
Code: plot_accX.m
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 34
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 arr1([1 3 5]) is [1.1 3.3 5.5] >> arr2 = [1 2 3; -‐2 -‐3 -‐4; 3 4 5]; >> arr2(:, [1 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 35
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]) What is the size of Hsub?
What are the elements of Hsub?
Using end in indices
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 36
• M(1:3:end,3:4:end)
M has 7 rows "end is 7 1:3:end = 1:3:7
M 7 rows
10 columns
M has 10 columns "end is 10 3:4:end = 3:4:10
Quiz: Matrix indexing
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 37
• Msub = M(1:end-1,2:end)
end is 7 1:end-1 = 1:6 = [1 2 3 4 5 6]
M 7 rows
10 columns
end is 10 2:end = 2:10 = [2 3 4 5 6 7 8 9 10]
• Questions: – Which rows of M
are in Msub?
– Which columns of M are in Msub?
Plotting experimental data (3)
• In the first experiment, you shook the car at 5 different frequencies and observed the amplitude of vibration
• After the experiment, you decided to find out more about what happens at frequencies 0.55, 0.60, 0.65 and 0.70
• How can you insert new data?
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 38
Frequency Amplitude 0.10 0.2 0.25 0.3 0.50 0.4 0.75 0.4 1.00 0.25
Frequency Amplitude 0.55 0.45 0.60 0.60 0.65 0.65 0.70 0.50
Insert new data here
Quiz: Merging vectors
Code in mergeVectors.m
ENGG1811 © UNSW, CRICOS Provider No: 00098G W7 slide 39
>> % Frequency vector #1 >> freq1 = [0.1 0.25 0.5 0.75 1.0]; >> % Frequency vector #2 >> freq2 = [0.55 0.6 0.65 0.7]; >> % Aim: We want to use freq1 and freq2 to form the vector >> % freq = [0.1 0.25 0.5 0.55 0.6 0.65 0.7 0.75 1.0]
Quiz
• The file walk.txt contains accelerometer measurements from a smart phone.
• The file is imported into Matlab
• The matrix walk has 4 columns – Column 1 is time – Column 2 is acceleration in the x-direction – Column 3 is acceleration in the y-direction – Column 4 is acceleration in the z-direction
• How will you plot acceleration in y-direction versus time?
• How will you plot time acceleration in y- and z-directions versus time?
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 40
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 41
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 elementwise multiplication:
a(i,j) * b(i,j)
a * b matrices matrix multiplication a × b
Division a ./ b arrays elementwise division:
a(i,j) / b(i,j)
a / b matrices = a * inv(b)
Left division a .\ b arrays elementwise 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 42
Operations • Precedence:
parentheses exponentiation, left-to-right unary plus and minus multiplication and division, left-to-right addition and subtraction, left-to-right Full list: 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 – Those with . are the array ops
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 43
Examples
• If it has a dot, then it’s an array op
>> 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 44
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. Be careful if you need to handle complex numbers.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 45
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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 46
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 (in K) and material characteristics:
– R is the ideal gas constant = 8.314 J/K/mol
– 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 47
Exercise
1. Compute the diffusivity of Ferrite for 40 equally spaced temperature from 25 °C to 1200 °C
2. Display results on plots of diffusivity against inverse temperature 1/T with different scale types
Using array operations • Given the temperature vector T, how can we use the
array operation to calculate
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 48
RTQ
eDD−
= 0
for each value of in the vector T
⇥T (1) T (2) T (3)
⇤
hD0e
� QRT (1) D0e
� QRT (2) D0e
� QRT (3)
i
• Starting point
Using array operations (2)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 49
h� Q
RT (1) � QRT (2) � Q
RT (3)
i
T =⇥T (1) T (2) T (3)
⇤
h1
T (1)1
T (2)1
T (3)
i1 ./ T
-(Q/R)./T
Using array operations (2)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 50
hD0e
� QRT (1) D0e
� QRT (2) D0e
� QRT (3)
i
he�
QRT (1) e�
QRT (2) e�
QRT (3)
i
h� Q
RT (1) � QRT (2) � Q
RT (3)
i
exp(-(Q/R)./T)
D0*exp(-(Q/R)./T)
Hint for array operations
• Write the normal scalar expression
• Identify the element-wise multiplication, division and exponentiation (i.e. to a certain power) – Change * to .*, / to ./ and ^ to .^
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 51
D0*exp(-(Q/R)./T)
D0*exp(-(Q/R)/T) Scalar
Array
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 52
Initial version using only plot()
Linear scales don’t show the relationship well enough.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 53
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)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 54
Quiz: 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 (in K) and material characteristics:
D = D0 (T )e
−QRT
• If the diffusion coefficient D0 is not a constant but depends on the temperature T according to:
D0(T) = a T2 + b T + c
Where a, b and c are some constants.
Question: How will you compute D.
Note: This is made up but test how you use Matlab
Quiz (continued)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 55
(a*T.^2+b*T+c) .* exp(-(Q/R)./T)
(aT 2 + bT + c)e�QRT
(a*T^2+b*T+c) * exp(-(Q/R)/T)
We want to calculate this for an array T
If T is a scalar: we write
Can you identify where we need to add a .?
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 56
More on built-in functions
• Many useful functions are provided – 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 57
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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 58
Formatting
• Default command window display format shows 4 digits after the decimal point – can change in Preferences, or use the format command – format long is a good alternative – Use help format for full list
• The disp function constructs message from array of strings
• 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 59
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 – line structure reflects shape (row order)
– command is load name.dat
– data is assigned to array variable name
• 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
ENGG1811 © UNSW, CRICOS Provider No: 00098G W8 slide 60
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