4E03 2018 Review notes A PDF

Title 4E03 2018 Review notes A
Author Daniel Lim
Course Digital Computer Process Control
Institution McMaster University
Pages 19
File Size 267.1 KB
File Type PDF
Total Downloads 58
Total Views 145

Summary

review notes...


Description

4E03/6E03 Review notes A: MATLAB Kamil A. Khan September 1, 2018 Several of the assignments in this class (and the 6E03 project) will involve implementing numerical methods in MATLAB; learning to do so effectively will be a major takeaway from this course. If you’ve never used MATLAB before, or if you’re feeling rusty, then these notes are designed to get you up to speed, and to help you approach scientific computing in general. There are a lot of suggestions here; take them with a grain of salt. Make sure that you’ve got MATLAB installed and working on your computer; I’m using version R2017a on a Mac, but whatever you’ve got is probably fine too. MATLAB is useful, but it’s not so prevalent in industry. This is because non-academic MATLAB licenses are expensive, and because MATLAB’s convenience comes at a severe cost of computational time, particularly for larger problems. If you ever need to learn programming languages like C++, Python, Julia, R, or Fortran in the future, you’ll find that much of your MATLAB intuition will still apply there. There’s a free alternative to MATLAB called Octave; it can do MATLAB’s basic operations, but its ability to handle dynamic systems, optimization, and process control is severely limited (as of this writing).

Basic computation When MATLAB opens, you’ll see a “Command Window”, where you can type in a command at a prompt labelled >>, and then press [Enter] to send it to MATLAB to chew on. If MATLAB doesn’t like what it receives, then it will show an error message that will usually be jargon-heavy but helpful. MATLAB has all the usual scientific-calculator functions you’d expect, with the asterisk * denoting multiplication, and the caret ^ denoting powers. Try typing simple scientific-calculator-style expressions, pressing [Enter], and seeing what you get. You can throw in spaces for style; MATLAB ignores them. Here’s a test of a classic trigonometric identity: >> sin (0.6 + log ( 3.0))^ 2 + cos (0.6 + log ( 3.0))^ 2 ans = 1

If you’re evaluating complicated expressions by hand or using a calculator, it’s helpful to evaluate and write down intermediate quantities for later use, especially if they occur

1

repeatedly. This philosophy extends to MATLAB, which can write intermediate quantities into your computer’s RAM and use them later. To do this, you’ll have to give these intermediate quantities a name, which can be just about any reasonable-looking string of symbols that isn’t one of MATLAB’s twenty sacred keywords. (The “iskeyword” command provides a list of these; it’s worth reading that list at least once.) In the example above, I could’ve used an intermediate variable to represent the repeated value 0.6 + log 3 as follows. >> a = 0.6 + log (3.0 ) a = 1.6986 >> sin ( a )^2 + cos ( a )^2 ans = 1

The equals sign “=” means that we’re assigning “a” to be the value 0.6 + log 3, regardless of anything else “a” may have previously meant. Names of variables and functions are case-sensitive, so MATLAB thinks that “A” and “a” are completely different things, and “Cos” is not the familiar trigonometric function “cos”. In the above example, suppose that we aren’t fussed about the numerical value of a. Such unwanted outputs can (and should) be suppressed with line-ending semicolons: >> a = 0.6 + log (3.0) ; >> sin ( a )^2 + cos ( a )^2 ans = 1

Unfamiliar functions and operations If you’ve never used a particular MATLAB operation before, or if you’re unsure what it does or how to use it, then use MATLAB’s help command in the Command Window. In the long term, you’ll find this more helpful than Googling. For example, is log the base-10 or base-e logarithm? Who knows, but let’s ask MATLAB: >> help log log Natu ral log ari th m . log ( X) is the n at ur al loga ri th m of the elem en ts of X. Comp lex resu lts are pro duc ed if X is not pos iti ve . See also log1p , log2 , log10 , exp , logm , real log . Ref ere nc e page for log Other fu nc tio ns name d log

2

Those “See also” entries are hyperlinks in MATLAB (but not in these notes!), which are useful when the function you’ve asked about is almost-but-not-quite what you want. Here we see that log is the base-e logarithm. If we wanted the base-10 logarithm instead, then “log10” in the “See also” section looks promising; clicking its link would show that it is indeed log10 . Some MATLAB commands are overloaded: they can do different things depending on the number of inputs they receive. One such function is max. MATLAB’s help is particularly useful when navigating these waters. You can also do the following: • “help elfun” (without the quotes) gives you a helpful hyperlinked list of every elementary scientific-calculator function MATLAB knows. For example, it tells us that “sqrt” is the command for computing square roots. Good to know! Operations involving complex numbers are listed here too. • “help elmat” gives a similar list for operations on vectors and matrices. More advanced linear algebra operations are listed in “help matfun”. • “help slash” describes MATLAB’s endearing backslash-based commands for solving linear equation systems such as Ax = b. • “help punct” lists the functions of symbols like “@” and “...”. This is particularly useful, since these symbols can’t be looked up on their own through commands such as “help @”. • “help ctrlmodels” gives a list of specialized functions in MATLAB’s Control System Toolbox; we’ll be using several of these in this course. • Entering “help” on its own gives a (long) meta-list of help topics, including all of the above. • Shouting “why” into the void gives a silly pseudo-random answer.

Vectors and matrices MATLAB’s greatest strength is its convenient handling of vectors and matrices. (Newfangled programming languages like Julia are similar in this respect, but wrestling with linear algebra in C++ or Fortran is a pain.) Column vectors are entered in MATLAB using square brackets, with components separated by semicolons. The vector b := (2, 5, 6, 0) would be entered as: >> b = [2.0; 5.0; 6.0; 0.0] b = 2 5 6 0

3

Apostrophes in MATLAB denote the transposing operation (·)T , for vectors and for matrices. With b defined as above, b’ denotes the row vector bT : >> b ’ ans = 2

5

6

0

We can pick out components of b using parentheses, with “b(1)” denoting the first component b1 , “b(2)” denoting the second component b2 , and so on. (Many other programming languages would refer to b1 as “b(0)” instead; be careful!) The final component of b can be picked out as “b(end)” without knowing its index. Subvectors can be specified by listing the range of included component indices using colons. >> b (2) ans = 5 >> b (1:3 ) ans = 2 5 6 >> b (2: end ) ans = 5 6 0

Addition of vectors works as you’d expect: >> b + b ans = 4 10 12 0

If you want to apply a scalar operation componentwise to a vector (or matrix), then throwing the vector into the operation directly will often work. For example, sin, exp, and scalar addition are automatically applied to each component of a vector separately. >> exp ( b) ans =

4

7.3891 148 .41 32 403 .42 88 1.0000 >> b + 3.0 ans = 5 8 9 3

Multiplication (*), division (/), and powers (^) do not work this way; they tend to refer to matrix-related operations instead (like matrix-matrix products). If you want to apply these componentwise, then write a dot before the operation: >> b ^2 Error usin g ^ One ar gum ent must be a squ are ma trix and the other must be a sca lar . Use POWER (.^) for el em ent wi se po wer . >> b .^2 ans = 4 25 36 0 >> b .* b ans = 4 25 36 0

I was lucky here in that my incorrect expression b^2 threw an error; it’s unfortunately possible that your incorrect code might be valid MATLABese for an unintended operation, in which case MATLAB would cheerfully produce numbers that aren’t what you want. For safety, in MATLAB, I always use dots when using scalar multiplication, scalar division, and scalar powers whenever vectors or matrices are involved, unless I specifically want the linear-algebra-related analogs of these operations. Components of vectors (and matrices) may be modified: >> b (2) = 7.0 b = 2

5

7 6 0 >> b (3) = b (3) - 1.0 b = 2 7 5 0

If you try to assign values to components that don’t exist, then MATLAB will quietly extend your vector until they do exist: >> b (6) = 12.0 b = 2 7 5 0 0 12

This operation seems convenient but is a computational bottleneck; it’s the computer equivalent of making a dinner reservation for five people, and then turning up to the restaurant as a group of twelve. It’s best not to use this size-extending feature at all; instead, start with a vector with the dimensions you want, and modify its components when necessary. When setting up a vector of a certain size, even if you may want to change its values later, helpful functions are: • zeros (create a vector or matrix full of zeroes; note the quirky spelling), • ones (create a vector or matrix full of ones), and • linspace (create a row vector comprising evenly spaced points between two numbers). Colons are also useful for creating vectors based on arithmetic progressions. These end up being row vectors; throw in a transposing apostrophe if you want a column vector. >> a = 2:9 a = 2

3

4

5

6

7

8

>> a = 23:( -2):1 7 a =

6

9

23

21

19

17

Matrices are handled a lot like vectors. They’re entered row-by-row, top-to-bottom, with successive rows separated by semicolons, and with the elements of each row separated by commas (or spaces). For example, the matrix   3.4 −2 0 A := 1 0 −4.5 is entered in MATLAB as: >> A = [3.4 , -2.0 , 0.0; 1.0 , 0.0 , -4.5] A = 3.400 0 1.000 0

-2.0000 0

0 -4.5000

Elements of a matrix may be picked out by entering the row-index and column-index via parentheses, and submatrices may be specified similarly. A lone colon “:” denotes “all indices”, and is useful for extracting rows or columns of matrices. >> A (1 ,2) ans = -2 >> A (2 ,2: end ) ans = 0

-4.5000

>> A (1:2 , 2:3) ans = -2.0000 0

0 -4.5000

>> A (2 , :) ans = 1.000 0

0

-4.5000

>> A (: , 2) ans = -2 0

7

The zeros and ones functions are very useful for initializing a matrix of a certain size, so that you don’t have to modify its size later on. Matrices (and vectors) may be glued together provided that their dimensions are compatible, using the same notation that’s used to construct a matrix from scratch. >> [ A , ( A + 1. 0) ] ans = 3.400 0 1.000 0

-2.0000 0

0 -4.5000

4.400 0 2.0000

-1.0000 1. 0000

1.000 0 -3.5000

>> [ A ; (2.* A )] ans = 3.400 0 1.000 0 6.800 0 2.000 0

-2.0000 0 -4.0000 0

0 -4.5000 0 -9.0000

MATLAB has a full suite of linear algebra operations, listed under the help topics I mentioned in the previous section. It’s never appropriate to compute a matrix inverse in a numerical method, either as inv(A) or A^(-1). This is because matrix inverses are computationally expensive, and can introduce unnecessary (and sometimes devastating) numerical errors. If you’re faced with an expression that seems to involve matrix inverses, then try instead to make creative use of linear equation-solves; see “help slash”.

Scripts and functions The Command Window is useful for trying out MATLAB’s features and functions, but in meaningful projects, it’s far better to write your MATLAB code in a separate file; such MATLAB scripts should be saved with the extension .m . Suppose you’ve grown fond of the example at the start of this document, and you want to record it as a script. To do this, start by creating a folder for this project; every separate coding project you pursue should have its own folder. Then, navigate to this folder in the “Current Folder” field in MATLAB. Create a script using the edit command and a descriptive filename (without spaces) of your choice: >> edit t rig Tes t .m

After a prompt, this new file will appear as a blank slate in a separate “Editor” window. Here, you can enter the commands you would’ve entered in the Command Window, with each command on a separate line. When you press the “Run” button in the menu bar (it looks like a green ◮ symbol), then these commands will be carried out by MATLAB in order, until either the end of the script is reached, or an error occurs. Our example here has only two lines, which we can easily type and save in the Editor window: 1 2

a = 0.6 + log (3.0 ) ; si n (a ) ^2 + co s (a ) ^2

8

Try running it. The result shouldn’t surprise you. For meaningful projects, there are several advantages to using a script rather than the Command Window: • If you make a mistake in an early line, it’s relatively easy to fix. Similarly, parameters (such as “a” in this example) can be modified easily. • It’s easy to re-run a scripted method. Once you’ve typed a script, you don’t have to type these lines again each time you want to run it; you can just run the script again. This makes your work reproducible. • A script is a reasonably permanent record (if you back up your computer!) of what you’ve done, which is crucial for scientific work. • Your code’s all in one place (namely, the folder you created for this project), so it’s easy to store, and easy to share with your boss or coworkers. (You’re on your own for the coding assignments in this class though!) You should back up your work frequently, either to an external hard drive or a server. For small projects that aren’t confidential, online services like Github, Dropbox, or Google Drive may be fine. When working on any professional coding project (beyond the scope of a class assignment), you should also implement version control using a program such as Git or Subversion. Version control lets you document any significant changes to your code, allows you to revert to previous versions (e.g. if you’ve changed your code and find that it doesn’t run any more), and helps multiple people work on the same code without trampling each other. In professional contexts, your company or institution’s IT department should be able to help you with both maintaining backups and using version control. We can make one more useful tweak to our script by turning it into a function. MATLAB functions start with the word “function”, and end with either “return” or “end”. 1 2 3 4

fun cti on tr igT est () a = 0.6 + log (3.0 ) ; si n (a ) ^2 + co s (a ) ^2 return

If a script is represented as a function, then this function’s name (after the word “function”) must match the script’s filename (without the “.m”) exactly. So far, this function behaves like the previous script; try running it. In the Command Window, we can invoke our function by entering its name: >> tr igT est () ans = 1

I’ve added optional parentheses at the end of the function name, because I want to make sure that my functions look different from my variables. We can even invoke this function from a second script/function in the same folder. 9

MATLAB functions can have inputs and outputs, just like mathematical functions. Let’s replace the “0.6” and “3.0” numbers in our example by generic user-specified inputs u and v, and have the output recorded as a quantity z instead of being displayed to the Command Window automatically. 1 2 3 4

fun cti on z = tr ig Te st ( u , v ) a = u + log (v ) ; z = sin ( a) ^2 + cos ( a) ^2; return

Now, in the Command Window, I can throw in arbitrary inputs, collect the output (namely, whatever value z takes when MATLAB reaches the “return” statement), and then process that output: >> b = tri gTe st (3.0 , 5.0); >> b + 2.0 ans = 3

As a downside, the “Run” button in the Editor window won’t work for functions with inputs, because MATLAB can’t figure out which inputs you want to feed to your function. Functions may also have multiple outputs, which are listed using square brackets. A similar function with three outputs might start with the line: 1

fun cti on [ z , t , Q ] = t ri gT es t (u , v )

In a script, if you enter the percentage sign “%”, then MATLAB will disregard the rest of that line, and the Editor will color it differently. You can use this feature to enter plainEnglish comments that describe your code. At the start of a function in a file, it’s helpful (to your colleagues and to future-you) to write a succinct description of its purpose and its inputs/outputs, and to include your name and the date: 1 2 3 4 5 6 7 8 9 10 11 12

% A si mple test of a t ri gon om et ri c identity , to pr act ice us ing MATL AB . % In puts : % u: a rbi tr ary numbe r % v: a rbi tr ary pos iti ve nu mber % Ou tput : % z: sho uld be 1 for any vali d input s % % Writ te n by Kam il Khan on F ebr ua ry 16 , 20 18 fun cti on z = tr ig Te st ( u , v ) a = u + log (v ) ; z = sin ( a) ^2 + cos ( a) ^2; return

That’s overkill for this simple example, but it’s very useful in “real” code. Now, in the Command Window, try entering: >> help t rig Tes t

You may be pleasantly surprised. When you’re writing a script in the Editor, MATLAB might express concern about your code-writing through “warnings” that appear in the scroll bar on the right side of 10

the window. Take these warnings seriously; they’re often genuinely helpful. Your finished code should have no outstanding warnings unless you have a very good reason for ignoring them.

Control flow Control flow refers to the order in which a computer carries out the commands in a script. So far, our scripts and functions have all had linear control flow: they require MATLAB to carry out a fixed series of operations from start to finish, like cooking a simple dish according to a recipe. (Control flow is often thought of in terms of cooking.) That’s sometimes all we need, but other situations call for more advanced control flow. This section describes how to use MATLAB for: • conditional statements, which make decisions about what code to perform based on a specified condition, • loops, which carry out repeated chunks of code, and • multiple functions, which can be used to organize code effectively. These can be very powerful, particularly in combination. There are fancier types of control flow (e.g. pertaining to object-oriented programming and parallel computing), but the above will be enough for this class.

Conditional statements Conditional statements allow us to write code to make decisions and proceed accordingly. As a cooking analogy, many cake recipes can be adapted to make cupcakes instead. When following these recipes, if you want to bake a cake, then you’d follow the basic recipe; if you want cupcakes, then you’d follow a slightly altered version instead. That’s a conditional statement in action. Suppose we want some commands to be carried out only when a variable x is positive. We can write this using an if-statement: 1 2 3 4 5 6

if x > 0.0 % this code is c arr ied out if x was positive , % ot her wi se MA TLAB will skip ah ead to 'end ' [ con di ti on al code ]; [ con di ti on al code ]; end

All sorts of elaborate conditions can be tested for in an if-statement; see “help relop” for a list. Note that equality is denoted as “==” rather than “=”. Since fractional real numbers (e.g. 10.3 or 31 ) are represented inexactly on computers, it’s usually not a good idea to use == to compare two real numbers that may take fractional values. This isn’t a problem when checking if two whole numbers are equal though. In our example above, suppose that we want certain alternative commands to be carried out if the test fails; that is, if x ≤ 0. This is accomplished using the else command. 11

1 2 3 4 5 6 7 8 9 10

if x > 0.0 % this code is c arr i...


Similar Free PDFs