Docsity

MATLAB Basics: Understanding Numbers, Formats, and Functions - Prof. Panayotis Kevrekidis, Study notes of Mathematics

Toggle sidebar
bg1
MATLAB Basics
MATLAB numbers and numeric formats
All numerical variables are stored in MATLAB in double precision floating-point form.
(In fact it is possible to force some variables to be of other types but not easily and this ability
is not needed here.) Floating-point representation of numbers is essentially equivalent to the
“scientific notation” of your calculator. Specifically a (real) number xis stored in binary
floating point form as
xf2E
where fis called the mantissa and Ethe exponent. The exponent is an integer (positive or
negative) and the mantissa lies in the range 1 f2. This representation is entirely internal
to the machine and its details are not important here. (They are important when analyzing
carefully the performance of numerical algorithms.)
Similar formats using the conventional decimal system are available for MATLAB input
and output. These formats can be set in the File – Preferences menu in the MATLAB
command window. They can also be changed using MATLAB commands.
» format short
»pi
ans
3.1416
» format long
»pi
ans
3.14159265358979
» format short e
»pi
ans
3.1416e000
» 100*pi
ans
3.1416e002
What does this emean? The result 3.1416e000 just means 3. 1416 100where three
digits are allowed for the decimal exponent. Similarly the final answer 3.1416e002 means
3. 1416 102or, approximately, 314. 16. In the same way, 3.1416e002 means 3. 1416 102
or, approximately, 0. 031416
One final note on this first MATLAB session: clearly the constant is known and is built
into MATLAB to high accuracy with the name pi. You should therefore avoid using pi as a
variable name in your MATLAB sessions!
Strings and printing
In more advanced applications such as symbolic computation, string manipulation is a very
important topic. For our purposes, however, we shall only need very limited skills in handling
strings initially. One most important use might be to include Your Name and the Course as part
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12

Partial preview of the text

Download MATLAB Basics: Understanding Numbers, Formats, and Functions - Prof. Panayotis Kevrekidis and more Study notes Mathematics in PDF only on Docsity!

MATLAB Basics

MATLAB numbers and numeric formats

All numerical variables are stored in MATLAB in double precision floating-point form. (In fact it is possible to force some variables to be of other types but not easily and this ability is not needed here.) Floating-point representation of numbers is essentially equivalent to the “scientific notation” of your calculator. Specifically a (real) number x is stored in binary floating point form as

x   f  2 E

where f is called the mantissa and E the exponent. The exponent is an integer (positive or negative) and the mantissa lies in the range 1  f  2. This representation is entirely internal to the machine and its details are not important here. (They are important when analyzing carefully the performance of numerical algorithms.) Similar formats using the conventional decimal system are available for MATLAB input and output. These formats can be set in the F ile – P references menu in the MATLAB command window. They can also be changed using MATLAB commands. » format short » pi ans 

» format long » pi ans 

» format short e » pi ans  3.1416e 000 » 100*pi ans  3.1416e 002 What does this e mean? The result 3.1416e000 just means 3. 1416  10 0 where three digits are allowed for the decimal exponent. Similarly the final answer 3.1416e002 means

  1. 1416  10 2 or, approximately, 314. 16. In the same way, 3.1416e002 means 3. 1416  10 ^2 or, approximately, 0. 031416 One final note on this first MATLAB session: clearly the constant is known and is built into MATLAB to high accuracy with the name pi. You should therefore avoid using pi as a variable name in your MATLAB sessions!

Strings and printing

In more advanced applications such as symbolic computation, string manipulation is a very important topic. For our purposes, however, we shall only need very limited skills in handling strings initially. One most important use might be to include Your Name and the Course as part

of your MATLAB workspace in a simple, and automatic, way. This is easily achieved by using strings and the MATLAB print function fprintf in a special file called startup.m which will be executed automatically when you start MATLAB. Strings can be defined in MATLAB by simply enclosing the appropriate string of characters in single quotes such as  s’My Name’ results in the output s  My Name More complicated strings can be printed using the MATLAB function fprintf. This is essentially a C programming command which can be used to obtain a wide-range of printing specifications. Very little of its detail is needed at this stage. We use it here only to illustrate printing strings. If you want more details on advanced printing, full details are provided in your MATLAB manual. The use of fprintf to print the Name and Course information is illustrated by  fprintf(’ My Name \n Course \n’) My Name Course  where the \n is the new-line command. The final one is included to ensure that the next MATLAB prompt occurs at the beginning of the next line rather than immediately at the end of the printed string. To make this appear automatically every time you start MATLAB, simply create a file called startup.m which has this one command in it. To create this m-file, click the “New m-file” icon in the MATLAB window. Type the single line fprintf(’ My Name \n Course \n’) and then save this file with the name “startup”. By default, MATLAB will save this in a folder called Work which is where you want it to be. (In older versions of MATLAB, the default location may be different, but is still acceptable.) The function fprintf can be used for specifying the format of MATLAB’s numeric output, too. However, for our purposes, the various default numerical formats are usually adequate.

Editing in the Command Window

Although we have not yet done very much in the MATLAB Command Window, it is worth summarizing some of the basic editing operations available there. Most of the elementary editing operations are completely standard: BackSpace and Delete work just as in any other Windows-based program; Home moves the cursor to the beginning of the current line; End moves the cursor to the end of the current line;  and  move the cursor one place right or left; Ctrl  and Ctrl  move one word right or left. Ctrl-C and Ctrl-V have their usual effect of copying and pasting. There are some nonstandard editing shortcuts which are useful: Esc deletes the whole of the current line;

are often referred to as overwriting the value of x with its new value. Similarly the MATLAB commands  i1;  ii 2 result in the output i  3 Note the use of the ; to suppress the output from the first line here. There are some arithmetic operations which require great care. The order in which multiplication and division operations are specified is especially important. What is the output from the following MATLAB commands? » a2; b3; c4; » a/b*c Here the absence of any parentheses results in MATLAB executing the two operations (which are of equal precedence) from left-to-right so that  First a is divided by b, and then  The result is multiplied by c. The result is therefore ans 

Note here the default “variable” ans is used for any arithmetic operations where the result is not assigned to a named variable. This arithmetic is equivalent to a b

c or as a MATLAB command » (a/b)*c Similarly, a/b/c yields the same result as a / b c or^

a bc which could (alternatively) be

achieved with the MATLAB command » a/(b*c) Use parentheses to be sure MATLAB does what you intend!

MATLAB’s mathematical functions

All of the standard mathematical functions — often called the elementary functions — that you will meet in your Calculus courses are available in MATLAB using their usual mathematical names. Many other functions — the special functions — are also included; you will most likely come across some of these in later mathematics and, more especially, engineering courses. The elementary functions are listed in your User’s Guide. This listing includes several functions which will not be familiar to you yet, and several that we shall not deal with in this book. The important functions for our purposes are:

abs (x) Absolute value sqrt (x) Square root sin (x) Sine cos (x) Cosine tan (x) Tangent log (x) Natural logarithm exp (x) Exponential function, e x atan (x) Inverse tangent, or arctan asin (x) Inverse sine, or arcsin acos (x) Inverse cosine, or arccos cosh (x) Hyperbolic cosine sinh (x) Hyperbolic sine Note that the various trigonometric functions expect their argument to be in radian (or pure number) form — NOT in degrees which are an artificial unit based on the ancient Babylonians’ belief that a year was 360 days long! Forexample, » sin(pi/3) gives the output ans 

Shortly we shall see how to use these functions to generate both tables of their values and plots of their graphs. Also we shall see how to define other functions either as strings in the MATLAB command window, or more usefully, as function m-files which can be saved for repeated use.

Vectors and Matrices

In MATLAB the word vector should really be interpreted simply as “list of numbers”. Strictly it could be a list of other objects than numbers but “list of numbers” will fit our needs for now. These can be used to represent physical vectors but are much more versatile than that as we shall see. There are two basic kinds of MATLAB vectors: Row and Column vectors. As the names suggest, a row vector stores its numbers in a long “horizontal list” such as

1, 2, 3. 4, 1. 23, 10. 3, 2. 1

which is a row vector with 6 components. A column vector stores its numbers in a vertical list such as

fit a simple pattern.

A matrix is simply a rectangular array of numbers (or other objects). Thus a matrix is a row of columns in which each entry is a column vector of the same length, or a column of rows in which each entry is a row of teh same length. The entries are indexed in a similar way to vectors: A(2,3) refers to the element in Row2 and Column3. Thus the elements of a 3  4 matrix are labeled in MATLAB as follows:

A 1, 1 A 1, 2 A 1, 3 A 1, 4 A 2, 1 A 2, 2 A 2, 3 A 2, 4 A 3, 1 A 3, 2 A 3, 3 A 3, 4

Mathematically this same array is usually written as

A 

a 11 a 12 a 13 a 14 a 21 a 22 a 23 a 24 a 31 a 32 a 33 a 34

The same matrix is a row of columns

A :, 1, A :, 2, A :, 3, A :, 4

or a column of rows:

A 1, : A 2, : A 3, :

where in each case the : denotes a "wild card" meaning all entries. The use of : in MATLAB is more powerful than this suggests. The next section explains MATLAB’s : notation more fully. This : notation can also be used within teh subscripts of a vector or matrix. We shall see this in examples.

MATLAB’s : notation

The colon : has a very special and powerful role in MATLAB. Basically, it allows an easy way to specify a vector of equally-spaced numbers. There are two basic forms of the MATLAB : notation.  Two arguments separated by a : as in » v2 : 4 generates a row vector with first component  2 , last one 4 , and others spaced at unit intervals.Three arguments separated by two :’s has the effect of specifying the starting value : spacing : final value. For example, the MATLAB command » v–1:0.2:2; generates the row vector v  1. 0, 0. 8, 0. 6, 0. 4, 0. 2, 0. 0, 0. 2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0.

Remember the syntax is start:step:stop. Also the step can be negative. There are no practical restrictions on the length of such a vector (or, therefore, on the range or spacing which can be used). Of course very long vectors may have two negative effects: Computing times are likely to rise dramatically, and Output may take up so much room in the Window that you have no way of fathoming it — or printing it in reasonable time.  Don’t forget the use of a semi-colon ; to suppress output in the Command Window. There is another very useful aspect of MATLAB’s colon notation. It can also be used to specify a range of subscripts for a particular operation. We see this in the following example. » wv(3:8) w  –0.6000 –0.4000 –0.2000 0 0.2000 0. Note that the index of w still starts at 1, so that, for example, » w(3) ans  –0.

linspace and logspace

MATLAB has two other commands for specifying vectors conveniently.  linspace is used to specify a vector with a given number of equally-spaced elements between specified start and finish points This needs some care with counting to get convenient spacing. For example: » xlinspace(0,1,10) results in the vector [0, 0.1111, 0.2222, 0.3333, 0.4444, 0.5556, 0.6667, 0.7778, 0.8889, 1.0000]. Using 10 points results in just 9 steps. » xlinspace(0,1,11) gives the vector [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0].  logspace has a similar effect — except that the points are spaced on a logarithmic scale.

Tables of function values

We can use MATLAB’s vectors to generate tables of function values. For example: » xlinspace(0,1,11); » ysin(x); » [x’,y’] generates the output ans  0 0 0.1000 0. 0.2000 0. 0.3000 0. 0.4000 0. 0.5000 0.

» ac ans  3 4 5 6 » b/c ans  2.5000 1.5000 0 1. Mathematically the operation of division by a vector does not make sense. To achieve the corresponding componentwise operation, we use c. /a. Similarly, for powers we use .^as follows » c./a ans  2.0000 1.0000 0.6667 0. » a.^c % squares of components of a ans  1 4 9 16 » c.^a ans  2 4 8 16 % powers of c 2 Similarly the mathematical operation ab is not defined but we may wish to generate the vector whose components are the products of corresponding elements of a and b. » a.*b ans  5 6 0 8 » b.^a ans  5 9 0 16 » a./b Warning: Divide by zero. ans  0.2000 0.6667 Inf 2. Note the warning created by the division by zero in the third element of the final operation here.

String functions

The simplest user-defined functions in MATLAB are created as strings in the command window. If we may need to evaluate these for arrays of arguments, remember to use the “dot operations” where necessary. As an example, evaluate the function fx   2 x^3  3 x 1  x^2 for x  0, 0. 3, 0. 6,  , 3. » x0:0.3:3; » f’2x.^3-3x./(1x.^2)’; » yeval(f); » [x’,y’]

ans  0 0 0.3000 -0. 0.6000 -0. 0.9000 -0. 1.2000 1. 1.5000 5. 1.8000 10. 2.1000 17. 2.4000 26. 2.7000 38. 3.0000 53. The only difficulty here is remembering that each time we form products, quotients or powers of vectors, the corresponding dot operation must be used. However there is another major drawback to this simple approach. Every time we wish to evaluate the function f , we must ensure that the argument is stored in a variable called x. This may be inconvenient if we have several functions and arguments within a computation. For this reason, function m-files are a much superior way of creating and saving user-defined functions.

Function m-files

To create a new m-file, click the “New m-file” icon in the MATLAB command window. If the m-file is to be a function m-file, the first word of the file is function, we must also specify names for the function, its input and output. The last two of these are purely local variable names. These mimic the mathematical idea of defining a function

yfx

but then assigning, for example, zf  2 . This is just a shorthand for temporarily setting x  2, evaluating the output y of the function and assigning this value to z. Function m-files work the same way. To illustrate we again evaluate the function fx   2 x^3  3 x 1  x^2 for x  0, 0. 3, 0. 6,  , 3 but this time using a function m-file. The m-file could be: function yfun1(x) y2x.^3-3x./(1x.^2); Then the commands » v(0:0.3:3)’; » fvfun1(v); » [v,fv] generate the same table of output as before. Note that this time, the vector v is a column vector and, consequently, so is fv. There is no need for any transpose operations in the output line. MATLAB m-files can be much more involved than this, as you will see during your

particularly useful in distinguishing curves for monochrome printing. These styles are denoted by

solid line  dotted line : dashed line   dash-dot .

Colors

The colors available for MATLAB plots are yellow y green g magenta m blue b cyan c white w red r black k The color choice may be combined with any of the line styles or markers. The use of these is illustrated with the following commands. First the data vectors » x(-5:0.1:5)’; » ytwofuns(x); are used for our illustrations. The file twofuns.m is function ytwofuns(x) y(:,1)1./(1x.^2); y(:,2)x./(1x.^2); The matrix y has two columns the first of which has the values of 1 1  x^2

and the second

has the values of x 1  x^2

Perhaps the simplest method of obtaining multiple plots on the same axes is to use the command hold on. The effect of this is that the next plot will be added to the current plot window. To cancel this in order to produce a new figure, hold off can be used. The command hold acts as a simple toggle switch between these two states.

To obtain a plot of just the first of these functions, we can use » plot(x,y(:,1)) which produces a “blue solid line” graph like that below

(^0) -5 -4 -3 -2 -1 0 1 2 3 4 5

1

Blue, solid line is the default first graph generated by plot. To change this we use syntax such as ’m’ which would be added to the command to force magenta plus signs to be plotted. The command » plot(x,y(:,1),’k:’) yields the same curve plotted as a dotted black line. It is worth noting that these effects are reliable screen effects, and are usually reliable for printing directly from MATLAB. Sometimes when graphics such as these are copied into other documents, the printer drivers will convert all line styles to solid lines! To get the plots of both functions on the same axes — but with different linestyles — use a command such as  plot(x,y(:,1),’k’,x,y(:,2),’g- -’); which results in the first curve being plotted as a solid black line, and the second as a dashed green line. Note that the vector x is needed for both sets of data.

MATLAB program control

We consider the various ways of controlling the flow of a piece of MATLAB code. These include:  for loops — which enable us to have an operation repeated a specified number of times. This may be required in summing terms of a series, or specifying the elements of a nonuniformly spaced vector such as the first terms of a sequence defined recursively.  while loops — which allow the number of times the loop operation is performed to be determined by the results. This is often used in iterative processes such as obtaining approximations to the solution of an equation.  if  else  — which is used when different actions are to be taken depending on the value of some variable. A simple example would be in obtaining the maximum of two quantities. Often the else clause may not be needed when a command is to be performed only if some condition is satisfied while nothing is done if the condition is not satisfied. The condition itself may be a compound condition based on more than one “true-false” determination. We shall see

end

while loops

For many situations a loop is required but we don’t know in advance how many times its commands will need to be performed. One situation where this arises regularly is in obtaining repeated approximations to a quantity where we seek to achieve some specified accuracy in the final result. For example, if we set x  1 and then repeat the instruction » xcos(x) we will see that the values begin to settle down. Suppose we wish to compute these until they agree to within 4 decimal places. To achieve this we can use a while loop which is controlled not by a simple counter but by a logical condition. The loop » x11;x00; » while abs(x1-x0)1e- x0x1; x1cos(x0); end yields the final result x1  0. Note that we need two values in order to make the comparison. Therefore two initial values must be specified, and we must update them each time through the loop. Again while loops can be nested, while loops may contain for loops, and vice versa. The control of while loops can be more complicated than here. It can contain compound logical conditions.

Logical and relational operators

There are three basic logical operators which are important in MATLAB programming: & AND | OR ~ NOT The meanings of these should be fairly obvious. Just remember that the mathematical meaning of OR is always inclusive. The effects of these operators is simply summarized in the following truth table where T and F denote “true” and “false” respectively. In MATLAB these values are actually represented numerically using 0 for false and 1 for true. (Strictly, any nonzero equates to “true” so that some arithmetic can be done with logical values — if you are very careful !)

A B A&B A|B ~A

T T T T F

T F F T F

F T F T T

F F F F T

There are other logical functions in MATLAB. The details can be found in the User’s Guide. Generally, you should use   round the various components of compound logical conditions to be sure you have the precedence you intend. For example, (A&B)|C and A&(B|C) have very different meanings — just compare the two truth tables. The relational operators which are often used in testing are mostly straightforward:  Less than  Greater than  Less than or equal to  Greater than or equal to  Equal to ~  Not equal to Note especially the double  for logical testing of equality. The single  is only used in MATLAB for assignments.

if ... else ...

Finally, we introduce the basic structure of MATLAB’s logical branching commands. Frequently in programs we wish the computer to take different actions depending on the value of some variables. Strictly these are logical variables, or, more commonly, logical expressions similar to those we saw in defining while loops. There are three basic constructions all of which begin with if and finish with end. The simplest has the form if condition commands end in which the statements in the commands block are only executed if the condition is satisfied (true). If the condition is not satisfied (false) then the commands block is skipped. The second situation is if condition true_commands else false_commands end in which the first set of instructions, the true_commands block, are executed if condition is true while the second set, the false_commands block, are executed if condition is false.