week 9 matlab: control structures, functions, 3d …en1811/15s1/lectures/week09.pdf• matlab has...
TRANSCRIPT
ENGG1811 © UNSW, CRICOS Provider No: 00098G1 W9 slide 1
Week 9
Matlab: control structures, functions,
3D plotting
ENGG1811 Computing for Engineers
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 2
References
• Chapman (2012), parts of chapters 3 to 6, 8
– section 3.1 to 3.5
– section 4.1 to 4.4.3
– section 5.1, 5.2, 5.6
– section 6.1 to 6.2
– section 7.2
– section 8.3
• online documentation at mathworks.com
http://www.mathworks.com.au/help/matlab/index.html
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 3
Plot appearance
• Line and marker styles
– values encoded in a short optional string following each x, y pair in a plot-type command
• See Chapman Table 2-10
>> plot(x, y, 'b*-'); % more x, y, stylestrings can follow
Line colour, r=red, b=blue, g=green, w=white, c=cyan, m=magenta, y=yellow, k=black
Marker style, .=point, o=circle, x=x, *=star, s=square, v=down triangle, ^=up triangle, etc
Line style, -=solid, --=dashed, :=dotted, -.=dash dot
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 4
Additional control
• Additional characteristics of the lines and markers are
specified by extra pairs of arguments to plot of the
form
'propertyname', value,
Properties include
LineWidth – in pixels (integer)
MarkerSize – in pixels
MarkerEdgeColor – string, same codes as for lines
MarkerFaceColor – string, same codes as for lines
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 5
LaTeX formatting
• Labels, titles and legend text can be formatted using a
scheme used for typesetting mathematical documents
• LaTeX (pronounced ‘lay-teck’) embeds codes or escape
sequences using backslash and other special characters
\it{text} \bf{text} – italic, boldface*
_{text} ^{text} – subscript, superscript
\lambda \SIGMA – Greek lowercase (), upper ()
\circ \pm \neq \infty – symbols
\rightarrow \uparrow – arrow symbols (also left, down)
\_ \^ \{ \} \\ – literal _ ^ { } or \
• Can omit { } if a single character, for example \itx
• See Chapman Table 3-2
* Font style changes do not properly terminate in Matlab versions to 2012b
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 6
LaTeX equations in published docs
• The full LaTeX equation formatter is available when an
M-file is published, special sequences include
\frac{num}{denom} – fraction
\sqrt{eqn} – square root
\sum_{min}^{max} – summation
\int_{min}^{max} – integral
• Inline equations enclosed in $…$ inside comment
• Block equations enclosed in $$…$$ inside comment
• Inside these, algebraic variables are italicised while
standard functions like sin or tanh are not.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 7
LaTeX equation examples
gives this result (though
equations are images, not
scalable text):
If you are really interested,
try help latex (part of the
syms package, converts a
symbolic expression to a
LaTeX equation)
%% % Einstein's famous equation is $E = m c^2$. % % $$\sum_{i=1}^{\infty} \frac{1}{2^i} = 1$$ % % $$\int_{0}^{\infty} x^2 e^{-x^2} dx = \frac{\sqrt{\pi}}{4}$$
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 8
Polar plots
• Polar plots have angles 0 to 2 in place of x, and
magnitude (distance from the origin) in place of y
• Chapman Example 3.3 – cardioid microphone response
– gain (relative sensitivity) varies with angle (0 = directly in front) according to the formula
>> g = 0.5; % gain coefficient, characteristic of mic
>> theta = linspace(0, 2*pi, 121); % 360/(121-1) = 3 degrees
>> gain = 2.*g .* (1 + cos(theta)); % * also OK
>> polar(theta, gain, 'r-'); % red, solid, 1px line
>> title('\bfCardioid microphone gain versus angle \it{\theta}');
)cos1(2 ggain
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 9
Annotations
Not a full graphics editor, so results are only approximate
Figure window has a toolbar
to add elements and save
Plot browser
Add/edit legend
Select tool
View – Plot Edit Toolbar to access annotation tools such as arrows, shapes and text boxes
File – Save As (*.fig)
See Chapman section 3.3
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 10
Other plot types
• Chart types similar to OpenOffice Calc/Excel
bar(x,y) – vertical bar chart
barh(x,y) – horizontal bar chart
stem(x,y) – marker and vertical line
stairs(x,y) – like bar, but only top of skyline shown
pie(x, explode) – use with caution, or preferably not at all
compass(x,y) – polar with arrow to each Cartesian point
• If y is a matrix instead of a vector, each column is a
separate plot
– applies to all plot types that accept y values as second argument
• See Chapman 3.4 and 3.5
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 11
Decisions
• Boolean constants are true, false
internally represented by 1 (or nonzero) and zero
• Relational operators are almost the same, except
== is the equality operator for numbers (not =)
~= is the inequality operator for numbers (not <>)
• Boolean operators also use a different notation
&& is the and operator (not And)
|| is the or operator (not Or)
~ is the negation operator (not Not)
• && and || are shortcut operators, right hand side is not
evaluated if the answer is established by the left operand
non-shortcut operators are just & and |
quad2or3 = (x == 0 || y/x <= 0); % quadrant 2 or 4, incl axes
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 12
Boolean operations
• Don’t use == or ~= for strings, use strcmp(s1, s2) or
isempty(s) instead
• Built-in Boolean functions include
isempty(a) – a has no elements (empty array), includes
empty strings
ischar(s) – s is a string (character array)
isinf(v) – v is infinite (the special value Inf)
isnan(v) – v is not a defined number (the special value NaN)
isnumeric(v) – v is a numeric array
logical(x) – interpret x as a Boolean, any non-zero is
true
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 13
Selection
• Matlab has if, switch and try/catch
– only if is essential for ENGG1811
• Same principle as for OOB but syntax differs slightly
if boolexpr1 statements1 elseif boolexpr2 statements2 elseif …
else
statementsn end
these are
optional
of course
% example (eps is predefined)
if abs(a-b) < eps
disp('a,b match');
else
disp('a,b differ');
end
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 14
Validation
• To avoid misleading or meaningless results, always
ensure that the problem instance parameters are
within the limits of the model
– the error function works like fprintf, but displays the
formatted message and where it occurred, then stops
– may not be practical to check all data values, especially a large externally supplied array
if numDataValues < 0
error('expected non-negative value for data size,
%d was specified\n', numDataValues);
end
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 15
Iteration – while
• Same principle as the while statement in OOB, syntax
is almost the same too
while BooleanExpression
statements
end
• Problem solving techniques that iteratively apply a
rule and ideally converge to a solution include
Goal seek (OO Calc)
Solver (OO Calc + Matlab’s ODE solvers)
Newton-Raphson (general)
Bisection (general, see next slide)
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 16
Bisection revisited
• Simpler than Newton-Raphson, but similar approach to
finding x such that f (x) = 0 for a known function f.
• Requires two points x1 and x2 such that the sign of f (x1)
is different from the sign of f (x2)
• By maintaining the opposite signs while moving the x
values closer, they converge on the root (at the rate of
log10 2 0.3 significant figures per iteration)
• Convergence criterion: relative difference <= eps
• Algorithm: evaluate f at the
midpoint
• Depending on its sign,
move either x1 or x2
2
21 xxxmid
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 17
Bisection implementation
• Full version in demos/bisection.m
% get function (as string funcExpr) and initial limits
% x1 and x2 from user
fx1 = fxeval(funcExpr, x1); % evaluate at x1
fx2 = fxeval(funcExpr, x2);
while ~ converged(x1, x2)
xMid = (x1 + x2) / 2;
fxMid = fxeval(funcExpr, xMid);
if sign(fxMid) == sign(fx1)
x1 = xMid;
else
x2 = xMid;
end
end
% x2 is the best estimate of the root
fxeval and converged
are in the en1811 folder;
sign is the built-in signum
function (returns –1, 0, or
+1 according to whether
its argument is negative,
zero or positive)
Schoenherr Line*
• Old formula estimates the coefficient of friction CF
of a ship, given Reynolds number , where
V – speed of vessel (m/s),
L – length of vessel (m) – kinematic viscosity of
seawater at 15°C, about 1.2210–6 m2/s
• For a 300m cruise ship travelling at 24kt
(12.3m/s), R ≈ 3.0e9
• Formula is
• Use the bisection script to solve for CF, which lies
between 1e–5 and 1e–1
– Note that the function expression can’t use any variables apart from the algebraic symbol x
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 18
VLR
0242.0
).(log10 F
FC
CR
* Example suggested by Phil Helmore, School of Mech & Manf Eng. Formula dates from 1947.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 19
Iteration – for
• Because Matlab is heavily array-based, the for loop
variable is assigned each value in an array in turn:
– The ArrayExpression is typically a vector generated with the colon operator
– the index variable is set to each value in turn (or each column if it’s a matrix)
– textbooks tend to use ii for row index variables and jj as
column index variables, reflecting the Mi j mathematical
notation but i and j are used to define complex numbers
– ENGG1811 convention is to use row and col (like OOB), or rowi and colj to maintain the matrix notation link
for index = ArrayExpression
statements
end
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 20
Examples
order = 10; % generate identity matrix M = eye(order)
for rowi = 1:order % can omit the increment as it’s 1
for colj = 1:order % nested loop: process columns
if rowi == colj
M(rowi, colj) = 1;
else
M(rowi, colj) = 0;
end
end
end
% factorial
n = 9; fact = 1;
for k = 1:1:n % we put the increment in this time
fact = fact * k;
end
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 21
Functions
• Functions come in different flavours
– global functions in an M-file with matching name
– local functions (or subfunctions), inside a function M-file
– nested functions (not used in ENGG1811)
– anonymous functions (not used in ENGG1811)
– function handles (useful in advanced programming, not in ENGG1811)
• Declaration is quirky:
• inputs are parameters, passed by value
• outputs can be any number of variables, including none
[ ] thus makes the function equivalent to an OO Basic Sub
function [outputs…] = functionname(inputs)
function body, using local variables
end
Tip: keep the [ ] even when there’s only one
return variable, avoids mistaking it for the
function name.
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 22
Inside the function
• Statements/commands have their usual meaning
– changes global environment through other functions calls, so plot() etc are fine
– local workspace, so new variables are local (as are parameters and output variables)
• Purpose: use input values, assign result(s) to output
variables
– return statement terminates the function early
– ENGG1811 convention for single return value is the name
retval (or return_value)
• To conform to doc standards, use the ENGG1811
newfunc command and fill in the comments
>> newfunc 'mygcd'; % edits new function file mygcd.m
% containing the function mygcd
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 23
mygcd
• Things to note about the implementation
– fill in the doc first, not as an afterthought
– acknowledge Euclid, he was the first to publish the elegant
converging GCD algorithm
– built-in nargchk validates number of arguments
• you can also allow optional arguments and test with
nargin, this is done in converged.m
– validation to avoid infinite loop if non-positive
• technically the algorithm would calculate gcd(0,0) = 0,
but gcd(0,b), b > 0 will fail. We reject all zero cases.
– OK to modify parameters, they are independent local
variables unlike OO Basic (and they can be any type)
– remember to return the result through retval (or other
named output variable(s)), Matlab only warns if there’s no
assignment to outputs anywhere
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 24
Local functions (subfunctions)
• If a function has a subtask that’s not general enough
for its own file, add a local function to the end
– accessible only within the parent file
– regrettably doesn’t apply to scripts (lazy people don’t want to create extra files, so they tend to bloat the script)
function [retval] = dostuff(args) % consists of three subtasks
subtask1
var1 = subtask2func(arr)
subtask3(var1)
…
function [ ] = subtask1() % no return value ~= OO Basic sub … end
function [retval] = subtask2func(vec) … end
function [ ] = subtask3(yyy) … end
Example – extend mygcd
• Add local validation function isint to check if
args are integers
– how? use floor(x) == x
– first version written to expect a single scalar, but can be extended to arrays:
[1,5] == [1,5] doesn’t return true as expected,
it returns [true, true] instead (actually [1,1])
isequal(x,y) used to compare arrays to yield a
single Boolean result
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 25
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 26
Workspace sharing
• Passing large arrays between functions can slow down
the program as a copy has to be made on each call
• Often you have several functions successively updating
an array
– variables can be put in a shared global workspace, separate from the workspace local to each script/function
– all functions and scripts need to declare global variables
– global variables use upper case by convention
function [ ] = updateImage() global CUR_IMAGE % alter some elements of this var
…
CUR_IMAGE(rowi, colj) = …
end
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 27
Data load/save
• Data can be saved in two simple formats
– .mat, a Matlab-specific format that preserves names, types and values from one or more variables
– ascii (text) format, data values only but readable with other applications
>> save mydata.mat image h vec % .mat format
>> save export.dat image –ascii % data only, space separated
>> load mydata.mat % reloads image, h and vec
>> load export.dat % stores result in variable export
• Loading from a mat file restores the saved variables,
overwriting them if necessary
• Loading from a text file (any extension except .mat)
stores into a variable named after the file
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 28
Other data sources
• Most data will come from other than Matlab
– Matlab can read from an Excel worksheet, but only numeric data (without using Matlab cell arrays, NCIE*)
– Array has extent based on first and last number found on any row or column, intervening values are NaN
>> data = xlsread('data.xls', 'sample'); % filename and sheet
>> size(data)
ans =
9 4 data = 123 NaN NaN 456 134 NaN NaN 834 145 NaN NaN 34 200 NaN NaN 125 211 NaN NaN 34 222 NaN NaN 456 233 NaN NaN 17 NaN NaN NaN 8 NaN NaN NaN 6
* NCIE means “not covered in ENGG1811”
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 29
Importing data from text files
• Other sources may be numeric (only) data in text files
– use csvread if data is CSV (comma-separated values)
– use dlmread if data has some other delimiter such as tab
– can use textread to obtain each column in separate
vectors, but this command is deprecated (obsolescent)
• Most flexible is textscan, but more complex file
operations and returns cell arrays (NCIE)
>> coords = dlmread('ThreeMileDamCoords.txt');
>> size(coords)
ans =
142 2
>> plot(coords) % oops, that’s not what we wanted!
>> plot(coords(:,1), coords(:,2)) % better
>> axis equal % restore the aspect ratio to 1.0
Coordinate axes would look better if the common multiple of 1000m were subtracted first. Matlab also has a mapping toolbox.
file is in a folder that is on Matlab’s path
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 30
3D line plots
• 3 dimensional line plots can be generated by passing
three equal sized vectors to plot3
• Example: decaying oscillations in a mechanical system
in two dimensions (Chapman 8.3.1)
t = linspace(0, 10, 200);
x = exp(-0.2*t) .* cos(2*t);
y = exp(-0.2*t) .* sin(2*t);
plot(x, y, 'Linewidth', 2); % 2D plot
title ('\bf2D Line Plot');
xlabel('\itx'); ylabel('\ity'); grid on;
…
plot3(x, y, t, 'Linewidth', 2); % 3D plot, time is z (up)
title ('\bf3D Line Plot');
xlabel('\itx'); ylabel('\ity'); zlabel('\itt'); grid on;
tetytetx tt 2sin)(2cos)( 2.02.0
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 31
3D time-based plot
• 3D plot shows the effect of time arguably better than
as distance along the 2D plot
• Even better, the 3D view
has interactive rotation
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 32
3D mesh and surface plots
• Data that has two independent variables (for example,
temperature measured at many coordinates in 2D
space) can be visualised as a 3D plot
– x and y are normally the independent variables
– z is normally the dependent variable
– can be displayed in three ways
1. as a mesh or wireframe of individual line plots
2. as a continuous surface, with colouring to highlight the slope at each point
3. as a series of contours, slices parallel to the x-y plane
– the catch is how the x, y and z arrays have to be specified
mesh(x, y, z);
surf(x, y, z);
contour(x, y, z);
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 33
3D plot arrays
• All three arrays have exactly the same shape
– the number of rows is equal to the number of y values
– the number of columns is equal to the number of x values
– this is slightly counter-intuitive but built-in tools help
– the x array specifies the x values in each row, duplicated
– the y array specifies the y values in each column
– the z array specifies the dependent value at each point
• Example, evaluated at x = 1, 2, 3
and y = 1.5, 3, 4.5, 6.
22),( yxyxz
708263246608286
408359244460984
242646056316233
354135000280281
666
5.45.45.4
333
5.15.15.1
321
321
321
321
. . .
. . .
. . .
. . .
zyx
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 34
3D plot arrays, continued
• Having the arrays structured this way allows you to
calculate the z value using array operators
• Fortunately you can easily construct the x and y arrays
from their respective vectors using meshgrid:
>> [x,y] = meshgrid([1,2,3], [1.5,3,4.5,6]); >> z = sqrt(x.^2 + y.^2);
>> surf(x,y,z);
>> xlabel('\itx');
>> ylabel('\ity');
>> zlabel('\itz');
Mesh doesn’t have surface
shading:
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 35
Problem instance parameters
• Good software development practices keep data and
processing logic separate as far as practicable
– data sets stored in external files, unless trivial
– constants in a separate class file NC, PM etc
– problem parameters should also be separately identifiable, distinguished from intermediate variables
• ENGG1811 convention: define parameters in a
separate section of the solution script
– prefix parameter name with p, then title case (since
they’re usually descriptive rather than algebraic)
– OK to have multiple sets, fully commented, the last set represents the ones in effect
– parameter initialisation and descriptive comment go together, so not needed in data dictionary
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 36
Example: boat hull*
A simple model for the hull of a boat is given by
where y is the width of the
hull from the centre line, x is
the distance along the centre
line, and z is the depth of the
hull. B is the beam (max
width), L is the length and D
is the draft (max depth).
This hull is 8m long, with 3m
beam and 1.5m draft.
* Based on Holloway, p.144 Project 15.
22
12
12 D
z
L
xBy
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 37
Implementing the model
• x and z are the independent variables, and range from
–L/2 to L/2, and –D to 0 respectively
– use linspace and meshgrid to generate these arrays
• The first half of the y values (the starboard side) are
produced by the formula, the second set of y values
has the opposite sign
– to display both halves (thus avoiding a huge maritime
disaster!), use the command hold on between plot
commands
– axis equal maintains aspect ratio (uniform scales)
• see boathull.m in the lecture package
– use the 3D rotation tool to examine the shape
– does mesh or surf give the better view?
– experiment with shading (faceted, flat or interp)
Coming up
• Assign 1 deadline Friday 5pm
– late penalty 15% off the max available mark per day
• Testing will start on the weekend
– every crash and dialogue box has to be acknowledged manually, could take a few days
• Assign 2 (Matlab, simple harmonic motion)
available by Thursday pm
– can be done singly, or in pairs from the same lab group
– due Friday week 11
– peer-assessed against objective criteria in lab12
• Final exam is scheduled for 8:45am Thu 18 June
– more info later, including sample exam + solutions
ENGG1811 © UNSW, CRICOS Provider No: 00098G W9 slide 38