Docsity

Intoduction to Matlab for beginners, Lecture notes of Mathematical Methods for Numerical Analysis and Optimization

Toggle sidebar
bg1
Chapter 2
MATLAB Basics
In this chapter, you will start learning how to use MATLAB to do mathematics.
You should read this chapter at your computer, with MATLAB running. Try
the commands in a MATLAB Command Window as you go along. Feel free to
experiment with variants of the examples we present; the best way to find out
how MATLAB responds to a command is to try it.
☞For further practice, you can work the problems in Practice Set A.The
Glossary contains a synopsis of many MATLAB operators, constants,
functions, commands, and programming instructions.
Input and Output
You input commands to MATLAB in the MATLAB Command Window. MAT-
LAB returns output in two ways: Typically, text or numerical output is re-
turned in the same Command Window, but graphical output appears in a
separate graphics window. A sample screen, with both a MATLAB Desktop
and a graphics window, labeled Figure No. 1, is shown in Figure 2–1.
To generate this screen on your computer, first type 1/2 + 1/3. Then type
ezplot(’xˆ3 - x’).
✓While MATLAB is working, it may display a “wait” symbol — for example,
an hourglass appears on many operating systems. Or it may give no visual
evidence until it is finished with its calculation.
Arithmetic
As we have just seen, you can use MATLAB to do arithmetic as you would a
calculator. You can use “+” to add, “-” to subtract, “*” to multiply, “/” to divide,
8
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b

Partial preview of the text

Download Intoduction to Matlab for beginners and more Lecture notes Mathematical Methods for Numerical Analysis and Optimization in PDF only on Docsity!

Chapter 2

MATLAB Basics

In this chapter, you will start learning how to use MATLAB to do mathematics. You should read this chapter at your computer, with MATLAB running. Try the commands in a MATLAB Command Window as you go along. Feel free to experiment with variants of the examples we present; the best way to find out how MATLAB responds to a command is to try it.

 For further practice, you can work the problems in Practice Set A. The

Glossary contains a synopsis of many MATLABoperators, constants, functions, commands, and programming instructions.

Input and Output

You input commands to MATLAB in the MATLAB Command Window. MAT- LAB returns output in two ways: Typically, text or numerical output is re- turned in the same Command Window, but graphical output appears in a separate graphics window. A sample screen, with both a MATLAB Desktop and a graphics window, labeled Figure No. 1, is shown in Figure 2–1. To generate this screen on your computer, first type 1/2 + 1/3. Then type ezplot(’xˆ3 - x’).

 While MATLAB is working, it may display a “wait” symbol — for example,

an hourglass appears on many operating systems. Or it may give no visual evidence until it is finished with its calculation.

Arithmetic

As we have just seen, you can use MATLAB to do arithmetic as you would a calculator. You can use “ + ” to add, “ - ” to subtract, “ ***** ” to multiply, “ / ” to divide,

8

Arithmetic 9

Figure 2-1: MATLAB Output.

and “ ˆ ” to exponentiate. For example,

>> 3ˆ2 - (5 + 4)/2 + 6*

ans =

MATLAB prints the answer and assigns the value to a variable called ans. If you want to perform further calculations with the answer, you can use the variable ans rather than retype the answer. For example, you can compute the sum of the square and the square root of the previous answer as follows:

>> ansˆ2 + sqrt(ans)

ans =

Observe that MATLAB assigns a new value to ans witheachcalculation. To do more complex calculations, you can assign computed values to variables of your choosing. For example,

>> u = cos(10)

u = -0.

Algebra 11

ans = x^3-3x^2y+3xy^2-y^ >> factor(ans)

ans = (x-y)^

 Notice that symbolic output is left-justified, while numeric output is

indented. This feature is often useful in distinguishing symbolic output from numerical output.

Although MATLAB makes minor simplifications to the expressions you type, it does not make major changes unless you tell it to. The command ex- pand told MATLAB to multiply out the expression, and factor forced MAT- LAB to restore it to factored form. MATLAB has a command called simplify , which you can sometimes use to express a formula as simply as possible. For example, >> simplify((xˆ3 - yˆ3)/(x - y))

ans = x^2+x*y+y^

 MATLAB has a more robust command, called simple , that sometimes does

a better job than simplify. Try bothcommands on the trigonometric expression sin(x)cos(y) + cos(x)sin(y)** to compare — you’ll have to read the online help for simple to completely understand the answer.

Symbolic Expressions, Variable Precision, and Exact Arithmetic

As we have noted, MATLAB uses floating point arithmetic for its calculations. Using the Symbolic Math Toolbox, you can also do exact arithmetic with sym- bolic expressions. Consider the following example: >> cos(pi/2)

ans = 6.1232e- The answer is written in floating point format and means 6. 1232 × 10 −^17. However, we know that cos(π/2) is really equal to 0. The inaccuracy is due to the fact that typing pi in MATLAB gives an approximation to π accurate

12 Chapter 2: MATLAB Basics

to about 15 digits, not its exact value. To compute an exact answer, instead of an approximate answer, we must create an exact symbolic representation of π/2 by typing sym(’pi/2’). Now let’s take the cosine of the symbolic representation of π/2:

>> cos(sym(’pi/2’))

ans = 0

This is the expected answer. The quotes around pi/2 in sym(’pi/2’) create a string consisting of the characters pi/2 and prevent MATLAB from evaluating pi/2 as a floating point number. The command sym converts the string to a symbolic expression. The commands sym and syms are closely related. In fact, syms x is equiv- alent to x = sym(’x’). The command syms has a lasting effect on its argu- ment (it declares it to be symbolic from now on), while sym has only a tempo- rary effect unless you assign the output to a variable, as in x = sym(’x’). Here is how to add 1/2 and 1/3 symbolically:

>> sym(’1/2’) + sym(’1/3’)

ans = 5/

Finally, you can also do variable-precision arithmetic with vpa. For example, to print 50 digits of

2, type

>> vpa(’sqrt(2)’, 50)

ans =

➱ You should be wary of using sym or vpa on an expression that

MATLAB must evaluate before applying variable-precision arithmetic. To illustrate, enter the expressions 3ˆ45, vpa(3ˆ45), and vpa(’3ˆ45’). The first gives a floating point approximation to the answer, the second — because MATLAB only carries 16-digit precision in its floating point evaluation of the exponentiation — gives an answer that is correct only in its first 16 digits, and the third gives the exact answer.

 See the section Symbolic and Floating Point Numbers in Chapter 4 for details

about how MATLABconverts between symbolic and floating point numbers.

14 Chapter 2: MATLAB Basics

Figure 2-2: Desktop with the Workspace Browser.

calculation by accident. Finally, we observe that the Workspace browser pre- sents a graphical alternative to whos. You can activate it by clicking on the Workspace tab, by typing workspace at the command prompt, or through the View item on the menu bar. Figure 2-2 depicts a Desktop in which the Command Window and the Workspace browser contain the same information as displayed above.

Errors in Input

If you make an error in an input line, MATLAB will beep and print an error message. For example, here’s what happens when you try to evaluate 3uˆ2 :

>> 3uˆ ??? 3u^ | Error: Missing operator, comma, or semicolon. The error is a missing multiplication operator *****. The correct input would be 3uˆ2*. Note that MATLAB places a marker (a vertical line segment) at the place where it thinks the error might be; however, the actual error may have occurred earlier or later in the expression.

Online Help 15

➱ Missing multiplication operators and parentheses are among the

most common errors.

You can edit an input line by using the UP-ARROW key to redisplay the pre- vious command, editing the command using the LEFT- and RIGHT-ARROW keys, and then pressing RETURN or ENTER. Th eUP- and DOWN-ARROW keys allow you to scroll back and forththroughall the commands you’ve typed in a MATLAB session, and are very useful when you want to correct, modify, or reenter a previous command.

Online Help

There are several ways to get online help in MATLAB. To get help on a particu- lar command, enter help followed by the name of the command. For example, help solve will display documentation for solve. Unless you have a large monitor, the output of help solve will not fit in your MATLAB command window, and the beginning of the documentation will scroll quickly past the top of the screen. You can force MATLAB to display information one screen- ful at a time by typing more on. You press the space bar to display the next screenful, or ENTER to display the next line; type help more for details. Typing more on affects all subsequent commands, until you type more off. The command lookfor searches the first line of every MATLAB help file for a specified string (use lookfor -all to searchall lines). For example, if you wanted to see a list of all MATLAB commands that contain the word “factor” as part of the command name or brief description, then you would type lookfor factor. If the command you are looking for appears in the list, then you can use help on that command to learn more about it. The most robust online help in MATLAB 6 is provided through the vastly improved Help Browser. The Help Browser can be invoked in several ways: by typing helpdesk at the command prompt, under the View item in the menu bar, or through the question mark button on the tool bar. Upon its launch you will see a window with two panes: the first, called the Help Navigator , used to find documentation; and the second, called the display pane , for viewing documentation. The display pane works much like a normal web browser. It has an address window, buttons for moving forward and backward (among the windows you have visited), live links for moving around in the documentation, the capability of storing favorite sites, and other such tools. You use the Help Navigator to locate the documentation that you will ex- plore in the display pane. The Help Navigator has four tabs that allow you to

Solving Equations 17

➱ To clear the value of the variable x, type clear x.

You can make very general assignments for symbolic variables and then manipulate them. For example,

**>> clear x; syms x y

z = xˆ2 - 2xy + y**

z = x^2-2xy+y

>> 5yz**

ans = 5y(x^2-2xy+y)

A variable name or function name can be any string of letters, digits, and underscores, provided it begins witha letter (punctuation marks are not al- lowed). MATLAB distinguishes between uppercase and lowercase letters. You should choose distinctive names that are easy for you to remember, generally using lowercase letters. For example, you might use cubicsol as the name of the solution of a cubic equation.

➱ A common source of puzzling errors is the inadvertent reuse of

previously defined variables.

MATLAB never forgets your definitions unless instructed to do so. You can check on the current value of a variable by simply typing its name.

Solving Equations

You can solve equations involving variables with solve or fzero. For exam- ple, to find the solutions of the quadratic equation x^2 − 2 x − 4 = 0, type

>> solve(’xˆ2 - 2x - 4 = 0’)*

ans = [ 5^(1/2)+1] [ 1-5^(1/2)]

Note that the equation to be solved is specified as a string; that is, it is sur- rounded by single quotes. The answer consists of the exact (symbolic) solutions

18 Chapter 2: MATLAB Basics

  1. To get numerical solutions, type double(ans) , or vpa(ans) to dis- play more digits. The command solve can solve higher-degree polynomial equations, as well as many other types of equations. It can also solve equations involving more than one variable. If there are fewer equations than variables, you should spec- ify (as strings) which variable(s) to solve for. For example, type solve(’2x - log(y) = 1’, ’y’)* to solve 2 x − log y = 1 for y in terms of x. You can specify more than one equation as well. For example,

>> [x, y] = solve(’xˆ2 - y = 2’, ’y - 2x = 5’)*

x = [ 1+22^(1/2)] [ 1-22^(1/2)]

y = [ 7+42^(1/2)] [ 7-42^(1/2)]

This system of equations has two solutions. MATLAB reports the solution by giving the two x values and the two y values for those solutions. Thus the first solution consists of the first value of x together with the first value of y. You can extract these values by typing x(1) and y(1) :

>> x(1)

ans = 1+2*2^(1/2) >> y(1)

ans = 7+4*2^(1/2)

The second solution can be extracted with x(2) and y(2). Note that in the preceding solve command, we assigned the output to the vector [x, y]. If you use solve on a system of equations without assigning the output to a vector, then MATLAB does not automatically display the values of the solution:

>> sol = solve(’xˆ2 - y = 2’, ’y - 2x = 5’)*

20 Chapter 2: MATLAB Basics

0 1 2 3 4 5 6 7 8 9 10

-0.

0

1

x

exp(-x) and sin(x)

Figure 2-

function data class. This is the type of input fzero expects as its first argument.

 In current versions of MATLAB, fzero also accepts a string expression with

independent variable x , so that we could have run the command above without using inline , but this feature is no longer documented in the help text for fzero and may be removed in future versions.

Vectors and Matrices

MATLAB was written originally to allow mathematicians, scientists, and engineers to handle the mechanics of linear algebra — that is, vectors and matrices — as effortlessly as possible. In this section we introduce these concepts.

Vectors and Matrices 21

Vectors

A vector is an ordered list of numbers. You can enter a vector of any lengthin MATLAB by typing a list of numbers, separated by commas or spaces, inside square brackets. For example,

>> Z = [2,4,6,8]

Z = 2 4 6 8

>> Y = [4 -3 5 -2 8 1]

Y = 4 -3 5 -2 8 1

Suppose you want to create a vector of values running from 1 to 9. Here’s how to do it without typing each number:

>> X = 1:

X = 1 2 3 4 5 6 7 8 9

The notation 1:9 is used to represent a vector of numbers running from 1 to 9 in increments of 1. The increment can be specified as the second of three arguments:

>> X = 0:2:

X = 0 2 4 6 8 10

You can also use fractional or negative increments, for example, 0:0.1:1 or 100:-1:. The elements of the vector X can be extracted as X(1) , X(2) , etc. For ex- ample,

>> X(3)

ans = 4

Vectors and Matrices 23

Matrices

A matrix is a rectangular array of numbers. Row and column vectors, which we discussed above, are examples of matrices. Consider the 3 × 4 matrix

A =

It can be entered in MATLAB withthe command

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

Note that the matrix elements in any row are separated by commas, and the rows are separated by semicolons. The elements in a row can also be separated by spaces. If two matrices A and B are the same size, their (element-by-element) sum is obtained by typing A + B. You can also add a scalar (a single number) to a matrix; A + c adds c to eachelement in A. Likewise, A - B represents the difference of A and B , and A - c subtracts the number c from eachelement of A. If A and B are multiplicatively compatible (that is, if A is n × m and B is m × ), then their product AB* is n × . Recall that the element of AB* in the i throw and j th column is the sum of the products of the elements from the i throw of A times the elements from the j thcolumn of B , that is,

( A ∗ B ) i j =

∑^ m

k = 1

A ik B kj , 1 ≤ i ≤ n , 1 ≤ j ≤ .

The product of a number c and the matrix A is given by cA* , and A’ represents the conjugate transpose of A. (For more information, see the online help for ctranspose and transpose .) A simple illustration is given by the matrix product of the 3 × 4 matrix A above by the 4 × 1 column vector Z’ :

>> AZ’* ans = 60 140 220

24 Chapter 2: MATLAB Basics

The result is a 3 × 1 matrix, in other words, a column vector.

 MATLABhas many commands for manipulating matrices. You can read

about them in the section More about Matrices in Chapter 4 and in the online help; some of them are illustrated in the section Linear Economic Models in Chapter 9.

Suppressing Output

Typing a semicolon at the end of an input line suppresses printing of the output of the MATLAB command. The semicolon should generally be used when defining large vectors or matrices (such as X = -1:0.1:2; ). It can also be used in any other situation where the MATLAB output need not be displayed.

Functions

In MATLAB you will use bothbuilt-in functions as well as functions that you create yourself.

Built-in Functions

MATLAB has many built-in functions. These include sqrt , cos , sin , tan , log , exp , and atan (for arctan) as well as more specialized mathematical functions suchas gamma , erf , and besselj. MATLAB also has several built- in constants, including pi (the number π), i (the complex number i =

and Inf (∞). Here are some examples:

>> log(exp(3))

ans = 3

The function log is the natural logarithm, called “ln” in many texts. Now consider

>> sin(2pi/3)*

ans =

26 Chapter 2: MATLAB Basics

Note that ^ has been replaced by .^. Now you can evaluate f1 on a vector:

>> f1(1:5)

ans = 3 7 13 21 31

You can plot f1 , using MATLAB graphics, in several ways that we will explore in the next section. We conclude this section by remarking that one can also define functions of two or more variables:

>> g = inline(’uˆ2 + vˆ2’, ’u’, ’v’)

g = Inline function: g(u,v) = u^2+v^

Graphics

In this section, we introduce MATLAB’s two basic plotting commands and show how to use them.

Graphing with ezplot

The simplest way to graph a function of one variable is with ezplot , which expects a string or a symbolic expression representing the function to be plot- ted. For example, to graph x^2 + x + 1 on the interval −2 to 2 (using the string form of ezplot ), type

>> ezplot(’xˆ2 + x + 1’, [-2 2])

The plot will appear on the screen in a new window labeled “Figure No. 1”. We mentioned that ezplot accepts either a string argument or a symbolic expression. Using a symbolic expression, you can produce the plot in Figure 2- withthe following input:

**>> syms x

ezplot(xˆ2 + x + 1, [-2 2])**

 Graphs can be misleading if you do not pay attention to the axes. For

example, the input ezplot(xˆ2 + x + 3, [-2 2]) produces a graph

Graphics 27

-2 -1.5 -1 -0.5 0 0.5 1 1.5 2

1

2

3

4

5

6

7

x

x 2 + x + 1

Figure 2- that looks identical to the previous one, except that the vertical axis has different tick marks (and MATLAB assigns the graph a different title).

Modifying Graphs

You can modify a graph in a number of ways. You can change the title above the graph in Figure 2-4 by typing (in the Command Window, not the figure window) >> title ’A Parabola’ You can add a label on the horizontal axis with xlabel or change the label on the vertical axis with ylabel. Also, you can change the horizontal and vertical ranges of the graph with axis. For example, to confine the vertical range to the interval from 1 to 4, type >> axis([-2 2 1 4])

The first two numbers are the range of the horizontal axis; both ranges must