This tutorial for MATLAB is kinda old, and needs lots of polish, but is left here in hopes that it is useful.
Using MATLAB in Calculus
Department of Mathematics, CSI
Last updated on
Welcome to the MATLAB tutorial.The intentions of this tutorial are:
- Be a guide to using MATLAB as a tool to study Calculus.
- Provide a quick way to get answers to MATLAB questions.
- Provide a collection of examples for your study of calculus and other math courses.
- Provide an archive of functions or m-files for your use.
- Be used as a starting point for web searches about MATLAB and mathematics. See the section on Resources .
- This tutorial is intended to be read on-line. This allows you to use the hypertext structure to move around the document with ease. You just point your mouse on a link and away you go. Use the back button on your browser to return to the previous screen. To orient yourself, there is a contents page and an index page .
- The contents page lists an outline of the tutorial. This is broken down by sections and subsections. This is useful if you know your topic and want to get there immediately.
- The index allows you to find references to a topic.
1 Other sources of help with MATLAB
If you are trying to find help with MATLAB you may want to try one of these:- On-line help is provided by the
help
command: For
example try this command to get help about the
plot
command:.
>> help plot
- You may find the web site of MATHWORKS
to be of help. Here you
will find
A collection of pre-written m-files .- information about the purchase of MATLAB.
- A technical notes FAQ (frequently asked questions).
- A list of books on MATLAB.
- other stuff...
2 Shortcuts
Included in this section are some tricks to make MATLAB easier to use.2.1 Windows stuff
The following shortcuts are for use with the Windows 3.1 version of MATLAB (version 4.2) that is installed in the computer labs. Newer versions may have different methods.- resizing the command window
To decrease the width of the MATLAB window, move the mouse pointer to the right border of the window. When the pointer is directly on the right border it will change to a double arrow. Press the left mouse clicker and while keeping it held down, move the mouse to the left. Notice that a highlighted line will appear denoting where the new right border will be. After you have re-positioned this vertical highlight about mid-screen, let go or the mouse clicker. Note that the MATLAB window is narrower, and that it is positioned on the left-hand side of the screen.
If you click on the upward-pointing arrow in the upper right hand corner of the MATLAB command window, the window will fill the whole screen and the button will turn into a double arrow. If you click on the double arrow, the window should return to its previous size.
- Moving the command window
Aim the mouse pointer at the title bar of the window. Then press the mouse left-hand clicker and, while keeping it pressed down, move the mouse, noting that a rectangular highlight moves along with it. This highlight tells us where the window will move to. Upon letting go of the mouse clicker, the window will be re-positioned there.
- Printing selected text
To print text from the command screen, you need first to select the text (mark a block of text). To do this, using the mouse, point to the beginning of the text. Press the left mouse button, and while holding down the button, move (drag) the pointer to the end of the text to be printed and then release the mouse button. You will see the selected text highlighted. Point to the ``FILE'' menu in the command window, click the left mouse button, and point to ``Print selected'' and click again. The selected text will be sent to the printer. (If this does not work, your computer may not be configured correctly---ask for help from a lab technician.) It is important that the desired text be first selected since, otherwise, the entire history of your MATLAB session will be printed---wasting a lot of paper!
- to print a graph from the figure window
To send your graph to the printer, click the mouse in the Figure Window. Then using the mouse, point the arrow to ``FILE" in the Figure Window and click the left mouse button. Then point the arrow to ``PRINT" and click again. Your figure will now be printed on the printer in the Computer Laboratory. WARNING: Make sure you are in the Figure Window -- if you are in the command window, MATLAB will print all your commands, from the start of the sessions.
- If the window you want is hidden, use Ctrl-Esc
(press the Ctrl key and Esc key at the same time). A box with a list of windows should appear. Click on the window you want, to select it, then click on ``switch to.''
- You can also use Alt-Tab:
pressing Tab repeatedly with the Alt key held down scrolls through the names of open windows. Release the Alt key when the window name you want appears. (These commands work in any Windows application.)
2.2 Command Line Editing
MATLAB has several tricks that will allow you to work faster when you work interactively.-
Using the Arrow keys
-
Moving to left and right along the line
The usual left and right arrow keys move you forward and backward along the line as you would expect.
- Exploring your command history
What is really convenient, is the use of the up and down arrows to scroll through your history. Hitting the up arrow puts the last command you entered in the command line. Hitting it twice will put the 2nd to last one. Guess what hitting it 3 times does? Did you go too far? Then the down arrow goes back down.
-
Moving to left and right along the line
- Moving along the line
MATLAB uses some keyboard shortcuts that are common in the UNIX world. In particular they come from the great editor emacs .-
Move to beginning of line
C-a: That's ``CONTROL - a'' pressed at the same time. The HOME key does the same. - Move to end of line
C-e: That's ``CONTROL - e'' pressed at the same time. The END key does the same - back one character
C-b: Same as left arrow. - forward one character
C-f: Same as right arrow. - ``kill'' all characters to the right
C-k: This will delete all the characters to the right of the cursor.
-
Move to beginning of line
-
The use of a ; can suppress the output:
Example:>> x = [1,2,3,4,5] % no semicolon ans = 1 2 3 4 5 >> x = [1,2,3,4,5]; % with a ``;'' there is no output
- several commands can be written on one line if separated
by semicolons (
;).
Example: The three lines>> x = linspace(0,6*pi); >> y = e.^(-x/10) * sin(x); % damped oscillation example >> plot(x,y);
could be one line>> x = linspace(0,6*pi);y = e.^(-x/10) * sin(x);plot(x,y);
3 How to work with numbers in MATLAB
To study Calculus using MATLAB we use a few features of MATLAB that allow us to store numbers, and lists of numbers.For a quick introduction click below, for a more thorough one, read on.
3.1 Quick introduction
A quick introduction to data typesWe make use of two types of data in using MATLAB for calculus: numbers, or scalars and lists or vectors. The words scalars and vectors are names given in a Linear Algebra course. How do we use these? Let's illustrate with an example:
Example: sin2 x plot
Plot the function f(x) = sin2(p x) over the interval [0,2 p]. Answer:
What do we need to do to plot this?
If x was a number say 5, then we would compute f(5) in MATLAB in a manner similar to a what is done on a calculator:
>> sin( pi * 5 ) ^2 ans = 0However, we will use the plot command. Plotting is discussed in the section of plotting functions . To use the plot command, we need to generate a table of numbers for the x- and y- coordinates. Of course we would like to do this in the easiest way possible.
-
First generate a list of numbers for the x coordinates. One
way to do
this is with the
linspace
command.
>> x=linspace(0,2 * pi); % generates 100 numbers between 0 and 6.28...
To take a peak at what you have done type (its a mess)>> x % yikes 100 numbers!
- Next we generate the y values corresponding to the x
coordinates. So for each value in the list for x we need to
create the value of f(x). That is we multiply by p, then we
find the sine, then we square. Now we want to do this for all the
values in the list at once and here is where we need to be
careful. If x was just a number or
scalar
, say x=5, we
would simply type what we have above.
>> sin(pi*x)^2 % Won't work for out x!!
However, this won't work as x is a list of numbers. And we need to tell MATLAB to treat it the right way. So we do this in steps:-
multiply x by p. This is a number times a list. MATLAB does
this as you would expect
>> pi * x % multiplies each element of x by pi
- find the sine of the new number. The new number is a list,
so we need to take the sine of a list of numbers. Again MATLAB is
smart enough to know how to do this:
>> sin(pi*x) % finds the sine of each element
- Finally we need to take the square. We can think of this as
multiplying two lists of numbers. How do we want this to be
done? Now it gets interesting. In linear algebra there is a very
common way to multiply vectors (or lists) called the
dot-product
. Here is
an example:
(1,2,3) · (1,3,5) = 1 · 1 + 2 · 3 + 3 · 5 = 22Notice, you match up the corresponding terms, multiply these and then add. This is the default way that MATLAB multiplies matrices .
We want something different: We want to match up corresponding terms, multiply and get a list when all is said and done. To do this in MATLAB you tell the multiplication to work ``element by element''. The special command for this is a ``.'': a period or a ``dot''. Here's how it works with the simple example above:>> [1,2,3] * [1,3,5] % gives an error >> [1,2,3] * [1,3,5]' % returns 22. the ' is transpose % (this is the dot product) >> [1,2,3] .* [1,3,5] % what we want a list ans = 1 6 15which is the list [1,6,15]. To multiply we put a ``.'' in front. As well this is necessary for division ./ and exponentiation (.^). Thus our plotting commands could be:>> x = linspace(0,2*pi); >> y = (sin(pi*x)).^2; % using the .^ notation as the % sin(pi*x) is a list >> plot(x,y); % enough already, make the plot
-
multiply x by p. This is a number times a list. MATLAB does
this as you would expect
3.2 Numbers and lists in MATLAB
The language of MATLAB is taken from that of Linear Algebra. It is important to understand a few different types of data. First we are all familiar with numbers. You should know the difference between the integers, the rational numbers, the real numbers and you may know the complex numbers. In linear algebra of MATLAB we call these scalars .Why do we need to give these a separate name? We also want to talk about lists or arrays of numbers. In Linear Algebra we may call these lists vectors . There is a mathematical connection made between a vector, which is a way to represent a magnitude and a direction, and a point on the graph. This is why MATLAB uses coordinates to represent vectors. An example might be the coordinates of a point on the graph: (4,5), or in 3 dimensions (3,4,5). Or, a list of x-coordinates that we wish to find the y coordinates for. As well, we can use a list as a shortcut to represent polynomials: for example f(x)= 5x2 - 6x + 12 could be associated with the list (5,-6,12).
This is really confusing if you are not careful. Let's look at a table of some different ways a mathematician like yourself can think of the list of numbers (1,2):
| (1,2) | the point (1,2) in the Cartesian plane |
| (1,2) | the vector associated with the directed line segment (0,0),(1,2) |
| á 1,2ñ | the same vector, only in another notation |
| [1,2] | the MATLAB notation for a row vector |
| [1;2] | the MATLAB notation for a column vector |
| [1,2] | a coding for the polynomial 1x + 2 |
| [1,2] | a way to represent the equation 1x = 2 in linear algebra |
We can also speak of two-dimensional arrays of data, much like the way we reference elements of a spread sheet. We may need two indices to speak about something: such as the first column and 2nd row has a value of 10. In shorthand we might write something like a21=10 and understand this to be shorthand for what we have in mind. Such things are referred to as matrices . Another example might be if we have two lists, say 10 x-coordinates and 10 y-coordinates. Then we might want the 8th x coordinate or the 6th y-coordinate. These could easily be referred to by a81 or a62. a final example is to represent a system of equations.
Example: The system of equations
| 7x + 5y + 0.1 z | = 100 |
| x + y + z | = 100 |
|
Now for the fun stuff. We may want to multiply these things together. You should be familiar with addition, subtraction, multiplication and division of numbers or scalars, but you might be surprised to know there are ways of doing such combinations to vectors and matrices as well that are important in many areas of mathematics.
You may ask ``How do we tell MATLAB that we are multiplying a scalar times a vector, or how do we tell MATLAB that we are multiplying a vector times a vector''. MATLAB is as smart as it can be about guessing, but you will have to supply the answer in some cases.
In particular, if in doubt MATLAB will assume you are referring to a matrix. So to really understand how MATLAB works, you need to know what matrix operations are.
3.3 Numbers or scalars
First we need to understand operations between scalars. This is easy as it is simply the arithmetic we are all familiar with.3.3.1 Usual Arithmetic
The simplest MATLAB commands are arithmetic operations which are the familiar operations of your calculator. These are represented by the following symbols: addition (+), subtraction (-),
multiplication (*), division (/), and exponentiation
(^). Try the following commands and observe the MATLAB
responses. After typing each line below remember to hit the
enter key to put MATLAB to work.
>> 3+4 % ans = 7 >> 5*9 % ans = 45 >> 8/9 % ans = 0.8889 >> 5^3 % ans = 125 >> sin(pi) % ans = 0. pi is the constant 3.14...Even better than a calculator, just like in Calculus, we can can make assignment statements to simplify or organize our work. here are some examples:
Example: Assignment to variables
>> a = 7; % the variable a is now 7
>> b = 2; a = 5; % b is 2, and now a is 5
>> c = a - 2; % c is now 5-2 or 3
>> a = a + 1 % a common computer statement.
% a is now 5 + 1 or 6
>> a,b,c % easy as a,b,c -- prints them out.
>> e = exp(0) % e is now e^1=2.71.... (no built-in
% constant like pi)
>> log(e) % ans = 0
>> x = 2;h=.01 % define some variables
>> fx = x^2; fxh = (x+h)^2 % f(x) = x^2, fx=f(x), fxh=f(x+h)
>> slope = ( fxh - fx )/h % slope of secant line
>> r = 5; % define the radius
>> area = pi * r^2; % area of a circle
>> r = 2.5; % oops before we had the diameter
>> area = pi * r^2; % We don't need to retype
% use th up-arrow
>> clear(a) % clears out the a variable
>> clear % clears out all variables
A few comments:
- Since spaces are ignored its a good idea to make your lines easy to
read
>> difficult=exp(sin(x^2-5*x+6*(4-3))) >> easy = exp( sin( x^2 - 5*x + 6*(4 - 3))) % trust us!
- If a command is followed by a semicolon (;) then MATLAB carries
out the operation but the result will not appear on the screen.
- Once a value is assigned to a variable, MATLAB remembers it until that variable is reassigned or cleared.
3.3.2 Order of Operations
First a ``quick and dirty'' answer, then a more thorough one.When you have a sequence of operations, it is always possible to force them to be performed in a certain order by using parentheses. For example, (5-2)/6 = 3/6=2, or 5-(2/6) = 5 - (1/3) = 14/3. However, one often wants to omit parentheses to avoid typing. MATLAB uses the standard order of priority (precedence) for operations: addition and subtraction have the same priority, as do multiplication and division. Exponentiation has higher priority.
Example: First assign values to a, b, and c as described above. For example:
>> a=8; b=2; c=16;Then we verify
Command Numerical Answer in Math language >> a - b * c -24 a - (b * c ) >> (a - b) * c 96 (a-b)*c >> a / b / c .25 (a/b)/c >> a / (b / c) 64 a/(b/c) >> a ^ b * c 1024 (a^b)*c >> a ^ (b * c) 7.9228e+28 a^(b*c) >> a ^ b ^ c Inf a^(b^c)To see a more detailed explanation read on.
MATLAB uses the following symbols for arithmetic operations:
| Operation | Symbol | Precedence | Comment |
| Exponentiation | ^ | 3 | Highest precedence |
| Multiplication | * | 2 | |
| Division | / | 2 | |
| Addition | + | 1 | |
| Subtraction | - | 1 | Lowest precedence |
If an arithmetic expression contains nested parentheses, then the expressions contained within the innermost parentheses are evaluated first. In the absence of parentheses, the precedence rules decide the order of evaluation. The following rules apply:
1. All operations with a higher precedence are carried out before those of lower precedences. Thus exponentiation is carried out first, then comes multiplication and division, and finally, addition and subtraction.
2. If two operations have the same precedence then the operation on the left is carried out first. This is called the left-to-right scan rule.
The examples in the following table show how the precedence rules help interpret arithmetic expressions based on these rules. Try them out on the computer and make sure that you understand how each expression is interpreted.
| Expression | MATLAB value | Interpreted as |
2*3+4*5 |
26 | (2*3)+(4*5) |
2+3*4 |
14 | 2+(3*4) |
(2+3)*4 |
20 | parentheses decides the order |
2/5*4 |
1.6 | (2/5)*4 |
2/(5*4) |
0.1 | parentheses decides the order |
2\^{}3\^{}2 |
64 | (2^3)^2 |
2\^{}(3\^{}2) |
512 | parentheses decides the order |
5/2/4 |
0.625 | (5/2)/4 |
5/(2/4) |
10 | parentheses decides the order |
3.4 Lists or vectors
What is a list or vector ? In MATLAB and linear algebra they are a way to keep track of several values at once. Here is how we can generate them:Example: How to generate lists
w = [1,3,5,7]; % the list 1,3,5,7
x = [1;3;5;7]; % take a peek at x and w to see the
% difference. A column vector!
y = 1:2:7; % again the list 1,3,5,7
z = linspace(1,7,4); % one more time
To generate w and x we used the MATLAB command to
specify a list member by member. The commas create a row
vector
, the semi-colons create a column
vector
. Take
a peek at the values of w and x to see the difference.To generate y we use the colon-operator , a shorthand way to generate evenly spaced values. The format is a:h:b. Which generates evenly spaced numbers starting from a to b in steps of size h. Finally, z is generated using the linspace command which by default generates 100 evenly spaced values between the two points given, in this case 1 and 7. By using a third argument, we specified the number of points, in this case 4.
For more details go click below:
3.4.1 Generating lists of data
We will see how generate lists of data. To be specific, we will call a list of data a vector .- Entering specific numbers
Example: Suppose you have a list of jogging times as follows: 30.45, 29.54, 31.16, 42.33 in minutes and seconds. To store these in a list we could type the following:>> times = [30.45, 29.54, 31.16, 42.33] % notice the [] and the commas , times = 30.450 29.540 31.160 42.330 % a row of numbers
or>> runs = [30.45; 29.54; 31.16; 42.33] % notice the semicolon ; runs = % a column of numbers 30.450 29.540 31.160 42.330There is a distinction made in MATLAB between rows of numbers and columns of numbers (row vectors and column vectors). MATLAB can switch between them with the transpose operator ' for example>> runs' % notice the ' sign runs = 30.450 29.540 31.160 42.330 % a row of numbers
The transpose operator can be useful when displaying your data.
- Extracting data
Suppose I have times entered in above, and I want to know the 1st jogging time. I can get at this as follows:>> times(1) % returns 30.450 >> times(3) % returns 31.160 >> times([1,3]) % returns 30.450 and 31.160
The last line uses a slice of the vector. It finds the 1st and 3rd times. This can be useful.
Example: Suppose we want to plot the line connecting (1,2) to (5,7). To plot the line we may want to enter the data as a table:>> x=[1,5];y=[2,7]; % the x-values and y-values
The command>> plot(x,y)
would plot a straight line segment between the points (1,2) and (5,7). What is its slopem = ( y(2) - y(1) )/ ( x(2) - x(1) ) % m = (7 - 2)/(5 - 1) = 1.2500
- evenly spaced numbers
If you had to enter the number 1 through 5 into a list you could
type
x = [1,2,3,4,5]
which isn't too bad, but suppose you had to do 1 through 100. You'd want a shortcut. Fortunately there is one using the colon-operator :x = 1:5 % same as x = [1,2,3,4,5]
The colon-operator creates a row vector .
If one wanted the even numbers between 1 and 10, we can do this easily as well using the colon-operator>> x = 1:2:10 % steps by 2. gives 1,3,5,7,9
The inside 2 means go in steps of size 2 starting from 1 until we get to 10 or bigger.
Noting that these are 5 evenly spaced numbers between 1 and 9, we could also use the linspace command>> linspace(1,9,4) % 4 is optional, without it you get % 100 numbersWhat is the 10th odd number? We could find this without thinking by>> x = 1:2:100; x(10) % x = 19
First, we need to understand Addition, Subtraction, Multiplication and Division between a scalar and a vector (or list).
For concreteness, lets define two variables, one will be a scalar , the other a list or vector :
>> x = 5; y = [1,2,3];The output is suppressed due to the ; at the end of each command.
Now lets look at each case:
-
addition What is x + y? This is a scalar plus a
vector. In linear algebra this isn't defined, but MATLAB says what the
heck you must mean we add the value of the scalar to each value of
the vector. So:
>> x + y % adds x to each value in y. Same with y + x ans = 6 7 8
- subtraction. Just like addition:
>> x - y % y - x subtracts 5 from each 1,2,3 ans = 4 3 2
- multiplication. This is scalar multiplication from
linear algebra. Each element of the vector is multiplied by the
scalar:
>> x*y % same as y * x ans = 5 10 15
Notice we use the ``*'' symbol for multiplication, just like usual. - division. Now we have to be careful. First dividing a
vector
by a
scalar
is what we expect -- each element
in the list is divided by the scalar
>> y/x; % gives ans = 0.20000 0.40000 0.60000
What about a scalar divided by a list? Let's try it:>> x/y % scalar divided by a list Warning: Warning: Will Rogers % MATLAB chews you out somehow
What went wrong? In Linear Algebra you can't divide by a vector . We'll see more on this later, but you may want to use the dot-operator . (>> x ./ y).
First for concreteness lets define some variables
>> w = [1,3,5,7]; % the row vector 1,3,5,7
>> x = [1;3;5;7]; % the column vector
>> y = linspace(1,7); % a list of numbers between 1 and 7 --
% a 100 numbers evenly spaced
-
addition and subtraction. What do we want. We have that
2*w is a vector whose entries are twice that of w,
so w+w should be the same: vector addition adds the
corresponding entries, keeping a vector for the answer.
>> w + w ans = 2 6 10 14
However trying to add w + x or w + y will give errors. In the first case the vectors have the same number of elements but are different shapes (a row vector and column vector). In the second case the vectors have a mismatched number of elements (w has 4 and y has 100)
moral number 1: to add or subtract vectors they must have the same shape and number of elements
moral number 2: If you try to add or subtract a vector and MATLAB chews you out, refer to moral number 1. - multiplication. There are two different multiplications
possible. One is the
dot product
the other is an element by
element product. The dot product can be viewed as a form of
matrix multiplication
-
dot product Its called the dot product because many
textbooks use a dot to represent it. For MATLAB it is a specific
case of matrix multiplication. To do the dot product we need two
vectors with the same number of elements, but the first one needs
to be a column vector and the second a row vector. (This is no
concern, because the
transpose-operator
'
switches back and forth.) We have w is a row vector and
x is a column vector. To do the dot product we write it
as usual multiplication
>> w * x % or used dot command ans = 84
Mathematically this took the matching elements in w and x and multiplied them, then added. Check that 84 = 1· 1+ 3 · 3 + 5 · 5 + 7 · 7.
- Element by element product.
If we want to multiply two lists ``element by element'' then we have to override MATLABs desire to do matrix multiplication. The dot-operator does this.
Example: squaring lists of numbers
Suppose we have a list of data representing measurements of radiuses of pipes, and we wanted to find the cross-sectional area of each one. That is we want to square and multiply by p. we could achieve this by>> rad = [12.2, 12.5, 12.0, 11.8]; % our data set >> rad2 = rad .* rad % the square. Could have been: % rad.^2. Notice the dot! >> area = pi * rad2 % or in one line: area = pi*(rad.^2)To use the dot-operator we need to have lists that are the same shape and size.
-
dot product Its called the dot product because many
textbooks use a dot to represent it. For MATLAB it is a specific
case of matrix multiplication. To do the dot product we need two
vectors with the same number of elements, but the first one needs
to be a column vector and the second a row vector. (This is no
concern, because the
transpose-operator
'
switches back and forth.) We have w is a row vector and
x is a column vector. To do the dot product we write it
as usual multiplication
Example:
>> a = 1 : 1 : 5 % creates array a = [1,2,3,4,5] >> b = 1 : 2 : 9 % creates array b = [1,3,5,7,9] >> a + b % vector addition -- no ``.'' needed ans = 2 5 8 11 14 >> 3*a - b % scalar multiplication. no ``.'' needed ans = 2 3 4 5 6 >> a * b % need a dot, or MATLAB will complain ERROR! That it not logical Spock! >> a.*b % notice the dot ans = 1 6 15 28 45Element by element multiplication, division and powers require a special dot operation: ``*'', "/", or ".^"
Example:
>> a./b % division needs the ``.'' ans = 1.0000, 0.6667, 0.6000, 0.5714, 0.5556 >> a.^2 % So does taking powers! ans = 1, 4, 9, 16, 25The dot preceding the asterisk or the slash or the symbol
`^' tells MATLAB to perform element by element array
multiplication, division, or exponentiation respectively.
Here are some additional examples where array mathematics have been used:Example:
Plot y=sin x + cos 3x over the domain [-p,2p] using steps of p /100:
>> x = -pi : pi/100 : 2*pi; y = sin(x)+cos(3*x); plot(x,y),gridNotice there is no need for a dot as we didn't use multiplication, division, or exponentiation of a list.
Example: Plot y = e-x/2cos 6x over the domain [0,p]:
>> x = linspace(0,pi); % or, x=0:pi/100:pi;
% or even (0:100)*(pi/100)
>> y1 = exp(-x/2); % built in function okay without dot
>> y2 = cos(6*x); % or, y = (e(-x/2)).*(cos(6*x))
>> y = y1.*y2; % need that dot for multiplication
>> plot(x,y),grid
Again note that the dot: ``.'' before the * means that
multiplication of the two arrays y1 and y2 is to be carried
out element-by-element. That is, each element of y is obtained by
multiplying the corresponding elements of y1 and y2.
Example: Plot y = x3 over the domain [-1,1]:
>> x = -1 : .05 : 1; % or use linspace >> y = x.^3; % we need that dot! its a power >> plot(x,y)
Note again that the dot before the exponentiation means that each element of the x array must be raised to the third power.
Example: Here is a special example about the syntax of MATLAB. Try this without the parentheses around the 1 before the ./ to see an error message.
Plot y = 1/(x2-1) over the domain [-2,2]:
>> x = -2 : 0.1 : 2; >> y = (1)./(x.^2-1); >> plot(x,y), grid % notice the discontinuities
You must put the parentheses around the 1 to prevent MATLAB from reading this as
>> y = 1.0/(x.^2 -1) % dividing by a list needs a dot!! Try again Homer!You could avoid having to think this out, if you remember that 1/x = x-1 and use
>> (x.^2 -1).^(-1) % double dots!
4 Symbolic Math
This section needs to be written.5 Functions
There are several ways you can use functions in MATLAB. There are built-in functions such as the sine and cosine functions, there are special means to deal with polynomials, there is the ability to work with symbolic functions and you can define your own functions using function m-files.5.1 Built-in functions
Listed below are some of the basic functions built into MATLAB.First the standard trigonometric functions , exponential functions and logarithmic functions.
Here are some functions that make the display of numbers nicer:
- format . Typical ones can be either short, long, or rat. For example the command >> format rat will cause the display to use fractions when appropriate
-
colon-operator
the construct
a:h:bwe'll call the semicolon operator. It generates a vector of numbers between a and b of step size h. - cross
The cross command find the
cross product
between 2 three-dimensional vectors.
- dot The dot command find the dot product between two vectors.
- dot-operator
The ``dot'' or period before an operator
such as * for multiplication, or ``/'' for
division or ``^'' for exponentiation. Tells MATLAB to
operate ``element by element'' or ``point by point''. For an example
look at a
dot operator example
- help The help command accesses MATLAB's built-in help facility. To try it out try the command: help plot.
- prod
The prod command takes the product of a
list of numbers, when given a matrix it takes the product of each
column returning a column vector. Here is how one could implement
the factorial command, n!:
>> n = 10; prod(1:n) % returns 10! = 3628800 = 10*9*8*...*1
- roots
The roots command find zeroes of a
polynomial. Click here to see
an example.
- sum
The sum command adds the entries in a
list or the columns in a matrix. For example, let's see that the sum
1 + 22 + 32 + ··· + n2 is a perfect square when n = 24.
>> n=1:24; % thenumber 1 through 24 >> a = sum(n.^2); % need a dot as n is a list >> sqrt(a) ans = 70 % a perfect square
Except for n=1 this is the only n for which this is true. Here is an example to simulate the number of heads in 100 coin tosses 250 times.>> r = rand(100,250); % 100 random numbers in [0,1] 250 times >> r = floor(r+.5); % takes integer part of r + .5 % this is a number 0 or 1 with equal % chance >> a = sum(r); % adds down the columns, giving 250 % numbers >> hist(a); % plot a histogram -- bell shaped - transpose-operator the symbol ' or single-quote indicates transpose. It switches a row vector into a column vector or vice versa.
- cylinder
Despite its name, this command plots a surface
of revolution of a curve around the z-axis. The curve is entered
in a vector of radius values. (That is you plot the surface given by
x2 + y2 = f(z)2.) To plot a sphere you could enter the
commands
>> z = -1:.1:1; >> r = sqrt(1 - z.^2); >> cylinder(r).
- grid puts a grid up during a plot command.
- linspace
The command linspace(a,b,n) generates
n points equally spaced over the closed interval [a,b]. Note that if
you wish to divide an interval into 10 equal subintervals, you need
11 points including the end points of the interval. If you omit
n then the command linspace(a,b) generates 100
equally spaced points over [a,b]. Similar to
colon-operator
.
- meshgrid
Like the
linspace
command, this
creates a matrix of x and y values to be used in plotting
three-dimensional graphs. It is used in the following manner:
>> [x,y] = meshgrid(-1:.1:1,-pi,:.1,pi);
- plot The plot command is used to plot lists of data. In its simplest use if x and y are the same size list, then plot(x,y) plots the x list verse the y list. More advanced features are possible. See the help page or click here.
- plot3 The three-dimensional plotting function. The command plots3(x,y,z) plots the points (xi,yi,zi) with a straight line connecting the point (xi,yi,zi) to (xi+1,yi+1,zi+1).
- sphere
Will plot a sphere. See
help spherefor more info. - surf
Creates a graph of a surface. It is called by
>> surf(x,y,z), where x, y and z are matrices. To use it you would typically create the values of x and y with the meshgrid command, and the value of z as a function of x and y. - view
This command changes the view or perspective of a
three dimensional graph. You can call it with two angles or a
vector. The vector is a three-dimensional vector that points in the
opposite direction than where you are looking from. For example,
view([1,1,1])will give a view of the origin as if you are looking from the point (1,1,1). - zoom The zoom command is usually followed by either an on or off. When on it allows you to explore the current plot with your mouse. ``Dragging'' out a window will force MATLAB to ``zoom in'' on that area. To undo this double click the mouse. As well, clicking in an area will force a similar effect.
5.2 Polynomials
There are a number of MATLAB commands that allow one to work easily with polynomials. For example: conv , deconv , poly , polyder , polyfit , polyval , roots . See the help commands if you can't find a definition.To use any of these built-in functions you need to be familiar with the shorthand convention MATLAB uses to store polynomials. Since a polynomial is determined by its coefficients (why?), it is only necessary to keep track of these numbers not the powers of x. For example, 15x3 - 6x + 12 is associated with the list (15,0,-6,12). Now a list in MATLAB can be a row vector or a column vector. MATLAB takes the convention that polynomials will be row vectors so the polynomial above would be
p = [15,0,-6,12] % notice commas not semicolons -- row vectorIf we wanted to find the roots of the polynomial 15x3 - 6x + 12, or the solutions to the equation 15x3 - 6x + 12=0 we could use the MATLAB command roots as follows
>> roots(p) % notice answer is a column vector ans = -1.07097 + 0.00000i % this is the real number -1.07097 0.53549 + 0.67841i % these two are complex conjugates 0.53549 - 0.67841iA general fact about polynomials tells us that a 3rd degree polynomial will have 3 roots. So we start with a row vector with 4 entries, and we get back a column vector with 3 entries.
5.3 Function m-files
If you want to explore many functions, it is tedious to keep retyping and/or using the Up Arrow key to repeat commands. Here we learn to simplify our work with script files and m-files .A script file will be a file that stores a sequence of keystrokes that makes it easier to reuse, or easier to edit if it is complicated.
An m-file (or function m-file) in MATLAB is the way subroutines are implemented. Knowledge of how to create m-files can make MATLAB a very powerful tool for studying mathematics.
-
SAVING COMMAND SEQUENCES IN M-FILES OR SCRIPT FILES
if you are working on the CSI network, and you do not already have a diskette in drive A you need to inform MATLAB where to find your personal script files. Try the command>. path(path,'a:\'); % or restart MATLAB with diskette in a:
To create a new script file in Windows 3.1:- Open the file menu (by clicking on FILE on the menu bar with the left mouse button);
- click on NEW in the menu; a sub menu will appear;
- click on the M-FILE option.
This will open a new untitled file in the Notepad editor (it is possible to set up MATLAB to use other editors). You should resize and arrange your windows so that it is easy to go back and forth between the MATLAB Command window and the Notepad window.
- You are know ready to go!
Script file exampleeg:script-file
Type in the following lines in the Notepad window. (Nothing will happen in the MATLAB window.) After typing a couple lines, choose Save As from the Notepad File menu. Save the file under the name ``limit.m'': you must use the extension ``.m'' or MATLAB will not recognize it. Choose Save from the File menu when you're done, but leave the Notepad window open. You will have written a program in the MATLAB language.
This program uses a shortcut: instead of writing x=[.1 .01 .001 ...], we write x=(.1).*(n) where n=1,2,3,...
%%%% this file should be saved as limit.m %%%% a % (percent sign) makes a comment to the end of the line clear % gets rid of old definitions format long % gives more digits in the answer n= 1:1:6; % the numbers 1 though 6 x=-(.1).^n; % the numbers 10^(-1) through 10^(-6) y=sin(x)./x; [x;y]' % limit from left in a table form x=(.1).^n; % or use x = -x with x above y=sin(x)./x; [x;y]' % limit from right in a table form
(Recall: MATLAB ignores text following a%.)
After saving the file, return to the MATLAB Command window (by clicking somewhere inside the window), and type>> limit % evaluates the file limit.m
Note that you don't type the ``.m''. MATLAB should begin to execute the commands just as if you had typed them in the Command window.
If you made an error while typing the file limit.m, MATLAB will halt on the line with the error and print out an error message. Simply return to the Notepad window, fix the error, Save the file, and try typinglimitagain in the Command window. If you already closed the Notepad window, Click on Open in the File menu (in the Command window), find limit.m in the file list and reopen the file.
Note: MATLAB does not find syntax errors before running the program since it uses an interpreter rather than a compiler (like C or Pascal).
moral: MATLAB beeps when it is trying to get your attention. This means it can't figure out what you mean. Pay attention and find out why it beeped, its just trying to help you.
- Function m-files
In order to create functions in MATLAB we need to have an understanding of how MATLAB handles the following computer related concepts
Format of the m-file: what is the syntax.- Input and Output of data: how to pass arguments
- looping: for loops
- Conditional expressions: how to direct the flow
- Calling the function from MATLAB.
Let's look first at an example to illustrate these points. The function n! in mathematics is shorthand for 1 · 2 ··· n. In MATLAB there is no built-in factorial function. Lets define one as fact. our function fact should have as its input a non-negative integer, and its output should be the factorial.function y = fact(n) % the function word is a non-comment. y % is the name of the output variable % and n is the name the m-file gives % to the input variable. if n < 0 % this line prints out an error message fprintf("factorial needs a non-negative integer\n"); % returns if there is an error return end y = 1; % initialize the value of y for i = 1:n % a loop y = y*i; end % end the loopLet's analyze the important lines.-
function y = fact(n)
This line follows the syntax of a function m-file. The first word if the keyword function. Then the return value or output, in this case the value of y. What does the return value equal, the function name without the .m extension, in this case fact, and then the input, in this case n. Hence when n is referred to in the file, it refers to the input value. -
if n < 0
This is the syntax for a conditional test. The simplest usage isif (CONDITION) THEN-BODY end
as in the factorial example. In general, it can beif (CONDITION) THEN-BODY elseif (CONDITION) ELSEIF-BODY else ELSE-BODY end
An example in general can be given with the heavyside function:function y = h(x) % save this a h.m if x < 0 y = -1; % so h(-5) = -1 elseif x = 0 y = 0; % h(0) = 0 elsif x > 0 % and h(5) = 1 y = 1; end
-
fprintf(stderr,"factorial needs a non-negative integer\n");
This is one way to pass a message back to MATLAB. The command fprintf is the print function, the word stderr tells MATLAB where to print the upcoming message (in this case where error messages go), and the line in quotes is the message. The\nis the end of line character.
-
for i = 1:n
This is main looping construct. This increases the value of i from 1 to n where n is the number given to fact when the function is called. The general syntax for a for loop isfor x = array COMMANDS end
Whew, that was a lot of work considering the following commands will find the factorial:
>> prod(1:n); % product of 1,2...n >> gamma(n+1); % gamma function is related to factorial
The array can be quite general. Here are some examples which can be run from the command line, or put into an m-file>> tot = 0; % our total >> for i = 1:2:100 % just the odd numbers > tot = tot + i; % you may have a different prompt >> end; tot % prints sum of odd numbers between 1 % and 99>> x = randn(1,100); % a list of 100 normally distributed % random numbers >> temp = 1:100; % the number 1 through 100 >> for i = temp(x < -2 | x > 2) % these are outliers in the data > x(i) = 0 % make outliers 0 >> endThe last example uses some a complicated way to get the array or list of numbers to index over. It takes only those indices for the list x which have x-values less than -2 or bigger than 2.
Another looping construct is the while command. This has the formwhile (CONDITION) BODY end
An simple example could be to construct the first n Fibonacci numbers. These numbers are 1,1,2,3,5,8,13,21,34,55 if n is 10.function fib = fib(n) % save as fib.m. return name same as % function name. That's okay! fib = ones (1, n); % fib = [1,1,1,1,1,1,1,1,1,1] if n=10 i = 3; while (i <= n) fib (i) = fib (i-1) + fib (i-2); % 1+1=2, 1+2=3, 2+3=5, 3+5=8 ... i=i+1; % increment i endThe while loops keeps looping until the condition that i be less than or equal to n is no longer true. The command ones is a simple way of making a sequence of all ones. Of course we should check that n is an integer bigger than 3. Don't forget to increment your expression or you'll find an infinite loop. (you can use the control-c key sequence to disable this.>> i = 1;while i < 2 > fprintf(``Help me! I'm stuck in an endless loop\n'') >> end
Some more examples of m-files:-
Evaluating functions from mathematics.
Suppose you wanted to evaluate the function f(x) several times in the course of a mathematical experiment. One way to type less is with an m-filefunction y = f(x) % save as f.m y = 1 - x.^2/2 + x.^4/4; % 5 terms in Taylor series for cosine % x. Notice the dotsThis was written so that both x and y could be lists of numbers. To use this we might do this in a MATLAB session>> x = linspace(0,pi); >> y = f(x);z=cos(x); % pass f(x) a list of numbers. No % problem. >> plot(x,y,x,z) % compare approximation to cosine x >> h=.01, difquo = (f(x+h) - f(x))/h % compute difference quotient >> plot(x,difquo,x,sin(x)) % compare difference quotient. - Writing your own
ezplot
.
Suppose you want to make plotting of a function simple, but you don't want to use ezplot as it works only for symbolic functions. Here is a simple m-file you could use. Can you think of any extensions you might make?function y = myezplot(f,a,b) %% myezplot: called with a function defined in an m-file, a and b %%graphs the function f defined in f.m over the range of %% values specified by the range [a,b]. If a and b are omitted it %% takes the interval [-5,5] as a default. if nargin = 1 a=-5;b=5 end for x = linspace(a,b) % loop over x in [a,b] y(i) = feval(f,i) % call the function in f.m. Needs to use % feval end plot(x,y);To call this function you would first define your function in a m-file, say yourfunc.m, then you would use the command>> myezplot(yourfunc,0,3) % plots yourfunc between 0 and 3
This example uses the variable nargin which is a count of the number of arguments in the input. As well it shows how you can pass a function name to a function. You need to use the command feval to evaluate the function.
6 Plotting functions
One of the most exciting uses of MATLAB is its ability to easily create the graph of a function. Suppose that we wish to plot the graph of the parabola y=x2 over the interval -2 £ x £ 2. How might we do this?If you wanted to plot this on a piece of paper, you might generate a table of numbers such as
| x | -2 | -1 | 0 | 1 | 2 |
| y | 4 | 1 | 0 | 1 | 4 |
Then you would plot each point (x,y) and connect the values with a curve which seemed appropriate -- in this case a parabola. Let's call this way of plotting ``x vs. y''.
Another way you might want to plot is to simply tell the computer to plot the function ``x2''. The command to plot a symbolic function will be ezplot .
MATLAB knows of other types of plots as well:
- Parametric plots: these allow you to plot x versus y only,
these are
parameterized by a third variable say t for time. Here's an example of
plotting the circle:
x(t) = cos(t), y(t)=sin(t); -2 £ t £ 2.
>> t =linspace(0,2*pi); >> x = cos(t);y=sin(t); >> plot(x,y); % notice we define x and y interms of % t, but we plot x vs y - Polar plots: to plot in polar coordinates
- Three-dimensional plots: plotting x, y and z.
- makemenus : Adds nice menus to plotting window which allow you to add text to graphs easily, to rotate axes, and other things. You can read about it in this file makemenu.README. The files are available on the MATHWORKS website, or on the math department site. At the math department site the windows files are in makemenu.exe and the UNIX files are here makemenu.tar.
6.1 Plotting x versus y
We see here how to plot functions, by plotting a table of values for x and y=f(x).Example: Cost of a used car
Suppose you were interested in buying a used car. You may want to know the relationship between number of miles the car has and the value of the car. Such numbers are available on the internet, for example these numbers were found at http://www.kbb.com. The price of a used 1996 Jeep Cherokee is figured according to the number of miles given. Here is some sample data:
| Mileage | Estimated Price |
| 5,000 | 23,225 |
| 10,000 | 23,050 |
| 20,000 | 22,900 |
| 40,000 | 19,900 |
| 60,000 | 17,600 |
| 80,000 | 16,800 |
| 100,000 | 16,500 |
>> mileage = [5,10,20,40,60,80,100]; % skip the thousands >> cost = [23.225, 23.050, 22.9, 19.9, 17.6, 16.8, 16.5]; % in thousands >> plot(mileage,cost)
From the graph we can see an interesting relationship not obvious from the table. For low, low mileage cars the graph is kind of flat prsumably as people believe the car is practically new, but as the mileage increases the cost decrease rapidly after a certain point. This may be explained by the realization that people shouldn't have to pay for the mileage already on the car, and the loss of warranty. The graph is more or less linear here. This eventually tails off as the mileage gets real high and the graph flattens out.
It is precisely the ability of plots or graphs to convey information quickly and clearly that makes them so invaluable. In this section you can learn how to create them.
6.1.1 Plotting lines
We all know that two points determine a line. What does this mean?We'll use MATLAB to plot the graph of a line using just two points.
First you may want to recall some basic formulas to describe lines:
Concept: Equations for lines
- The slope of a line:
Let (x1,y2), and
(x2,y2) be two points on a line. Then the slope of the line is
given by the rise over the run.
m = (y2-y1)/(x2-x1).
- Point-slope equation:
Let (x1,y1) be a
point on the line and m be its slope. Then the equation of the
line is
y = m (x - x1) + y1(Essentially you solve for y)
- Slope-intercept form:
Let m be the
slope and b be the y-intercept of a line (so (0,b) is a point
on the line) then
y = mx+b
- two points:
Let (x2,y2), and
(x1,y1) be two points on a line. Then
y = y2-y1 x2-x1 (x - x1) + y1
Example: For definiteness, we want to plot the line connecting (1,2) to (5,7). First lets define the points. How should we do this? Lets pair off the x values and the y values:
>> x=[1,5];y=[2,7];Now we can use MATLAB to reference the individual components if we need to. Notice how this is done:
>> x(1) ans = 1 >> y(2) ans = 7So we could compute the slope by
m = ( y(2) - y(1) )/ ( x(2) - x(1) )Or we could plot the line by
>> plot(x,y)
Notice this draws a line between our two points. What if we wanted to plot the line over a specified interval, say [0,5]. We have a slope, and a range of x values, and a point (1,2). Using the point-slope form we know we should use the formula y = m (x - x1) + y1. We know m and x1 and y1, what do we do with x and y?
When plotting, we need to make a table of values for x and a corresponding table of values for y. In MATLAB this is done by letting x be a list or vector or numbers and then creating y based on x. To do this we can use the linspace command:
>> x = linspace(0,5); % 100 evenly-space numbers between 0
% and 5
>> y = m * (x - x(1)) + y(1); % point-slope form
>> plot(x,y);
Example: plot of farenheit
Let's plot the relationship between farenheit and celsius. Recall the formula is F = 9/5 C + 32. The interesting range of values might be for celsius between 0 and 100.
>> celsius = linspace(0,100); % the domain >> farenheit = 9/5 * celsius + 32 % our formula >> plot(celsius,farenheit) % the plot >> hold on; >> plot(farenheit,celsius) % the inverse bunction
6.1.2 Plotting functions
Suppose that we wish to plot the graph of the parabola y=x2 over the interval -2 £ x £ 2. In the absence of MATLAB, we could choose a set of x values, say, x=-2,-1,0,1,2, then square each x value to determine the corresponding y values, y=4,1,0,1,4. We then mark each corresponding (x,y) pair as a point on a Cartesian coordinate system. These pairs are {(-2,4),(-1,1),(0,0),(1,1),(2,4)}. Finally, we try to connect these points smoothly to obtain a sketch of the parabola. To create a graph of y=x2 using only the same 5 points as described above, we can issue the following MATLAB commands.>> x=-2:1:2; % creates the array x=[-2 -1 0 1 2] >> y=x.^2; % creates the array y=[ 4 1 0 1 4]; note the ``dot" after x >> plot(x,y)
A brief explanation is in order. The first line defines x to be the list (or row vector ) of values starting with -2, continuing in steps of 1, and ending at 2. (This uses the colon operator .) The second line defines y as the array of values which are the squares of the x values. That is, the y list is obtained by squaring the x list element-by-element. See a description here of the dot operator ).
What you see should be a crude graph of the function y=x2 consisting of a sequence of broken lines connecting the (x,y) points calculated. To create the graph, MATLAB simply starts with the first point, connects it with a straight line to the second point, and connects the second point with a straight line to the third point, and so on. Thus every graph in MATLAB consists of a sequence of straight lines.
If you wish to obtain a smoother graph, all you have to do is use more points. But this requires no more labor on your part than using just 5 points. The following commands should create a much smoother graph as they utilize 201 points to construct the graph. Although it may no longer be evident, the graph still consists of a sequence of straight lines!
>> x=-2:0.01:2; % creates the array x=[-2 -1.9900 -1.9800 ... 1.9900 2] >> y=x.^2; % creates the array y=[ 4 3.9601 3.9201 ... 3.9601 4] >> plot(x,y)
Graphing functions -- more details
Here are a number of different examples of how we can use MATLAB to plot functions.
- Continuous Functions
A function f(x) is a set of ordered pairs (x,y) such that y=f(x). To create a graph of this function we first form two lists x=[x1,x2,...,xn], and y=[y1,y2,...,yn] where yi=f(xi), i=1,2,···,n and then issue the MATLAB command plot .
Example: Plot of y=ex
As an example, let us create a graph of the function y=ex describing each step in detail.
First decide the domain of the function and the desired frequency of plot points. Suppose that we let x vary from -1 to +1 in steps of 0.2. This is accomplished by the command:>> x = -1 : 0.2 : 1; % or use linspace(-1,1,11)
This creates an array with 11 elements starting at x = -1, increasing steps of .2 and ending at x = 1. If you do not type the `;' at the end of the command line you can see the array created asx = [-1, -.8, -.6, -.4, -.2, 0, .2, .4, .6, .8, 1]
Recall (Generating lists of data) for the explanation of the colon operator . (thatx=a:h:bgenerates an array of values starting at x=a, increasing in steps of `h' without exceeding x=b. Thus, this command will divide the interval [a, b] into n equal parts (n = (b - a)/h), thus sampling the domain at (n + 1) points including the two end points.
- For each value of x, calculate the corresponding value of
y. This is accomplished by the command:
>> y = exp(x);
Note that the built-in function exp(x) is defined such that if the argument x is an array, then it generates an array y of function values corresponding to each of the x values. Thus, y is now an array of 11 elements. If the semicolon at the end of the line is omitted you will see this array as:y = [.3679, .4493, .5488, .8187, 1.0000, 1.2214, 1.4918, 1.8221, 2.2255, 2.7183] - To obtain a continuous plot of ex over the domain
[-1,1], issue the command
>> plot(x,y)
The desired continuous graph will be created on the screen. Here, continuous plot means that MATLAB marks each ordered pair (xi,yi), i=0,1,2,...,n on the graph and then connects, by a straight line, the point (x0,y0) to (x1,y1), the point (x1,y1) to (x2,y2), and so on until the point (xn,yn) is reached. This graph created with 11 sample points is obviously not so smooth. Thus to obtain a smooth looking curve one needs to take sufficiently many x points depending on how rapidly the function varies over its domain. The following three commands may be used to obtain a smoother graph;>> x = -1 : 0.01 : 1 ; y = exp(x) ; plot(x,y),grid
We have added a grid command at the end to produce a set of grid lines on the graph. Note that we have used a smaller step size of 0.01 giving us 201 (2/.01 = 200) sampled points and therefore a much smoother graph.
-
Discrete plots
At times, instead of a continuous plot we may wish to obtain a discrete plot or point plot whereby the points are marked on the graph but they are not connected to each other by straight lines. In that case we need to specify the symbol we wish to use to mark each point. Supposing that the symbol is`*', the plot command becomes>> plot(x,y,`*')
Try this and see what happens.
MATLAB permits only a limited number of symbols to be used in discrete plot s. These are the symbols *, `.', `+',`x',`o'.
Example: Discrete Plots
To see the discrete points distinctly, you should use a reduced number of sample points, by taking a larger step size:>> x=-1:0.2:1; y=exp(x); plot(x,y,`*'), grid
which will produce a discrete graph with exactly 11 points.
A convenient way to control the number of points on a graph without calculating the corresponding step size over the domain of definition is to use the built-in function linspace . Using this function, the above graph can be obtained by entering>> x=linspace(-1,1,11); y=exp(x); plot(x,y,`*'), grid
More generally, the commandx=linspace(a,b,n);generates n points equally spaced over the closed interval [a,b]. Note that if you wish to divide an interval into 10 equal subintervals, you need 11 points including the end points of the interval. If you omitnthen the commandlinspace(a,b)generates 100 equally spaced points over [a,b].
- GRAPHING MORE THAN ONE FUNCTION ON THE SAME GRAPH
You can plot more than one function at a time by using the plot command in a extended way.
Example: Amplitude vs. Period
Let's investigate the relationship between the amplitude and the period for the cosine function. Recall
Concept: the generic form of a cosine function
y = a + d cos(b x + c).- The value of a determines the shift up or down the y-axis
- The value of |d| is the amplitude.
- The value of b determines the period by the formula T = 2p/b.
- The value of c determines the phase shift. (it is not c, but rather c/b.
>> x=0:pi/100:2*pi; y1=4*cos(x); y2=cos(4*x); plot(x,y1,x,y2), grid
By giving MATLAB data in this form it knows to graph both functions. Note that MATLAB decides a frame which fits in all function values, and then creates a plot of each function. If you have a color monitor, different colors will be used for each function.
Another way to achieve this is with the hold function:>> x=0:pi/100:2*pi; y1=4*cos(x); y2=cos(4*x); >> hold on; % prevents second graph >> plot(x,y1), grid % from over-writing the >> plot(x,y2) % first
The hold command has two uses hold on or hold off. This toggles whether or not MATLAB will try to draw the next graph without erasing the previous one.
Example: Secant line example
Concept: Definition of the secant line
The secant line is the beginning of the study of derivatives in calculus. It involves lines, and their slopes. The fundamental thing to know is the following definition:
The limit of the slope of the secant line (if it exists) is the derivative of the function.
Let y=f(x) be a function and let x1,x2 be two points in its domain and consider the secant line connecting the two points P1=(x1,f(x1)) and P2=(x2,f(x2)) on the graph of this function. The slope of this secant line is given bym=(f(x2)-f(x1))/(x2-x1).
This represents the average slope of the function f(x) on the interval [x1, x2].
Another way we see this written is to let h = x2 - x1 be the difference between the two points x2 and x1. Then the formula for the slope becomes
m=(f(x1+h)-f(x1))/h,
and the derivative of f(x) at the point x1 is given byf'(x1) = lim h® 0 (f(x1+h)-f(x1))/h.
To see the secant line and the function on the same graph, we need to plot both functions simultaneously. This is done via the hold command: Let f(x) = sin(x), and let x1 = p/4, and x2 = x1 + h where h = p/8. We'll plot the secant line and the function between 0 and p/2.>> x1=pi/4;h=pi/8;x=linspace(0,pi/2); % assign the constants >> m = (sin(x1+h) - sin(x1))/h; % find the slope >> ysin = sin(x); % the y values for f(x) >> yline = m*(x-x1) + sin(x1) % point-slope form of a line >> hold on; % turn on hold >> plot(x,ysin) % plots the function >> plot(x,xline) % plots the line
You should see both plots on the graph.
- GRAPHING FUNCTIONS OVER DOMAINS WITH DELETED POINT(S)
When we do not have a continuous function then we have to do more work to plot it with MATLAB.
Example: Deleted points in the domain
Plot f(x) =1/(x2-1) over [0,2]: Notice the function f(x) is a discontinuous function at x=1. First try typing:>> x = 0 : 0.05 : 2; y = (1)./(x.^2-1);^ plot(x,y), grid
What does the graph look like?
The function is undefined at x = 1. In processing you can avoid that point by dividing the domain into two parts. Notice we avoid the point x=1.>> x1 = 0 : 0.05 : 0.95; y1 = (1)./(x1.^2-1); >> x2 = 1.05 : 0.05 : 2; y2 = (1)./(x2.^2-1); >> plot(x1,y1,x2,y2),grid
Mathematically, we plotted the following function:f(x) = (x2 -1)-1 if x ¹ 0, f(0)=0.f(x) = ì
í
î1/(x2-1) 0 £ x < 1 1/(x2-1) 1 < x £ 2
- PLOTTING FUNCTIONS DEFINED BY MORE THAN ONE EQUATION
Many functions in Mathematics need to be defined in a piece-by-piece fashion. For example the absolute value function, or the greatest-integer function. To plot these we have to use MATLAB in a piece by piece fashion as well
Example: The sign function
Plot the following function, sometimes called the, sign function, over the interval [-3,3] defined as followsf(x) = ì
í
î|x| / x if x ¹ 0, 0 if x = 0
f(x) = |x|/x if x ¹ 0, f(0) = 0.
Define>> x1=linspace(-3,0); y1=abs(x1)./x1; % -3<x<0 >> x2=linspace(0,3); y2=abs(x2)./x2; % 0<x<-3 >> plot(x1,y1,0,0,'*',x2,y2), grid
Note that in the plot command, the single point at the origin is being marked with a `*' to make it visible. This one is not well suited for the hold command.
6.2 plotting with ezplot
6.3 Parametric plots
6.4 Polar plots
6.5 Three-dimensional plots
MATLAB has some abilities to work with 3-dimensional plots. In this section you can learn how to plot- a vector as a line segment.
- a plane in 3 dimensions.
- a cylinder , which mathematically speaking is more complex than your last can of Coke.
- surfaces of revolution .
- a vector-valued function as a parameterized curve.
- Functions of the form z = f(x,y).
You may find the makemenus m-files to be of use with manipulating the graphing window. Among other things, these allow you to use the mouse to rotate the viewing angle.
6.5.1 Three-dimensional plotting functions
To plot with three dimensions we use the following built-in MATLAB functions: meshgrid , plot3 , surf , view , sphere , cylinder .As well, we will define several short m-files that facilitate the plotting process. These use the MATLAB commands above to plot.
6.5.2 Plotting vectors
Plotting vectors is as easy as connecting two points with a line. Recall in two dimensions, to connect two points we use the plot command. An example is given here>> plot([1,5],[2,7]);This plots the line between the points (1,2) and (5,7). In other words, the command plot(x,y) plots the list of numbers in x versus those in y connecting the points (xi,yi) to the points (xi+1,yi+1). The plot3 command does exactly the same thing, only it needs three coordinates for a point as it plots three-dimensional points. So to connect the point (1,2,3) to the point (5,7,8) we could use the command
>> plot3([1,5],[2,7],[3,8]); % connects the two points with a lineNotice, you may have your points given in terms of a vector, say v=á 1,2,3 ñ to plot these you can access the individual components as follows
>> v = [1,2,3]; plot3(v(1),v(2),v(3)); % plots the point associated to
% the vector v
The simple
m-files
qvector.m will allow you to plot
a vector with the command qvector(v)6.5.3 Plotting planes
To plot a line in two dimensions you make values of x and corresponding values of y and plot the pair of lists. For example this will plot a line>> m = 5; b = 2; % y = mx + b >> x = linspace(-5,10); % plot the line between -5 and 10 >> y = m*x+b;plot(x,y); % make the plotWe need to do exactly the same thing to plot a plane in MATLAB. So we need to generalize the linspace command and go from there.
Concept: equation of a plane
Recall the equation of a plane which is normal to the vector v, and goes through the point P=(x0,y0,z0) is given by
n · á x - x0, y - y0 , z - z0 ñ = 0
or solving, if n = á a,b,cñ then one has
a x + by + cz = d = n · (P) = ax0 + by0 + c z0.
if c is not 0 then we can solve to get z = (d - ax - by)/c.
So to plot a plane we first generate a mesh of values for x and y, then we find z and then we plot using the surf command. Here is an example
>> n = [1,2,3];p=[3,2,1]; % normal to n, through p >> [x,y] = meshgrid(-1:.1:1, -2,.1:1); % meshgrid like linspace. >> z = (dot(n,p) - n(1) * x - n(2) * y)/n(3); % n(3) non zero >> surf(x,y,z); % plots the surfaceThe m-files qplane.m will automate this for you, and plot the vector as well.
An important command for viewing planes is the view command. This allows you to change perspective.
>> view(n); % called with a vector. What is the
% output?
>> view([-3,0,1]); % a vector parallel to plane. Where did
% the plane go?
>> view([1,1,1]) % view from the point (1,1,1)
6.5.4 Plotting Cylinders
Concept: Plotting Cylinders
In Calculus, a cylinder is defined to be all the points which lie on lines that are parallel to a given vector, and go through a given curve. For example, the usual cylinder we think of is made up of all points on the lines parallel to the z-axis, or the vector k, that go through the curve given by x2+y2=1.
To plot a cylinder then we could simply shift the curve in the direction of our vector and then trace out the curve, repeating this several times. Here is an example
>> t = (0:25)*pi/25; % or linspace(0,pi,25)
>> x = t; y = sin(t); % parameterize the sine curve
>> z = zeros(size(x)); % make z a list of 0's, the same size
% as x
>> v=[-1,-2,3]; % our vector
>> plot3(x,y,z);
>> hold on;
>> for k=(0:10)/10 % loop between 0 and 1 10 times
plot3(x + k*v(1),y + k*v(2),z + k*v(3)); % plot the curve shifted
end
This is automated by the
m-files
qcylindr.m
(notice the silly spelling). (This is different than the built in
MATLAB command
cylinder
which plots a surface of revolution
despite its name.)To use the qcylinder command, we need to trace out a parameterized curve in the x,y-plane, and pick a vector. Here are some examples
>> t = linspace(0,2*pi);x = cos(t);y=sin(t); >> qcylindr(x,y,[0,0,1]) % parallel to z-axis >> qcylindr(x,y,[0,1,1]) % parallel to the vector [0,1,1] >> x = linspace(0,6*pi);y = sin(x); % a sine wave cylinder >> qcylindr(x,y,[0,1,1]) % parallel to the vector [0,1,1]
6.5.5 Plotting surfaces of revolution
Concept: Surfaces of revolution
Surfaces of revolution are surfaces associated with equations of the form
x2 + y2 = [f(z)]2
or any permutations of the three variables. The one above is a
surface of revolution about the z-axis. Notice for a fixed value
of z. the curve is a circle with radius |f(z)|.
To plot a surface of revolution there is the MATLAB command cylinder. (A cylinder is a surface of revolution, as well as a mathematical cylinder.) If you don't like the language cylinder for a surface of revolution, you can use the m-files qsurfrev.m instead. Here are some examples, first Gabriel's horn (what is its volume? What is its surface area?)
>> z = linspace(1,100);r = (1)./z; % notice the dot >> cylinder(r); % or qsurfrev(r)Here is how a cylinder is a surface of revolution:
>> z = linspace(1:10); r = ones(size(z)); % all ones?? >> cylinder(r); % a cylinder!Here is cone:
>> z = linspace(1,10); m = 2; r = m*z; % cone with ``slope'' 2 >> cylinder(r); % or use qsurfrevHere is a sphere:
>> z = -1:.1:1; r = sqrt(1 - z.^2); % notice the dot >> cylinder(r); % or use qsurfrev
6.5.6 Plotting vector-valued functions
To plot a vector-valued function we need to associate a vector with a point. The point is the terminal point of the vector if its initial point is at the origin. Thus is the vector á 1,2,3 ñ then the point associated to this vector is the point (1,2,3). This is an easy concept to grasp, but is also very easy to get confused.A vector-valued function that we can plot should be a function of a single variable, returning a vector in 2 or 3 dimensions. For concreteness, we will consider functions of the type f(t) = á x(t),y(t),z(y)ñ. That is, the function returns a three-dimensional vector.
To plot, we simply associate the point with the vector, then this becomes the same problem as drawing a parameterized curve in three dimensions.
This will hopefully become clear with some examples:
Here is a helix: The function we are graphing is f(t) = á cos(t), sin(t),tñ.
>> t = linspace(0,4*pi); >> x = cos(t);y=sin(t);z=t; >> plot3(x,y,z); % plots the parameterized curveHere is a straight line given by a point and a vector:
>> p = [1,2,3]; v = [0,1,3]; % a point and a vector
>> t = linspace(-3,3);
>> x = p(1) + t*v(1); y = p(2) + t*v(2); z = p(3) + t*v(3);
>> plot3(x,y,z); % plots the line. Use view to get
% different views
Here is the flight of a baseball to right center
>> t = linspace(0,5); >> x = 100 * cos(pi/4) * cos(pi/6) t; >> y = 100 * cos(pi/4) * sin(pi/6)*t; >> z = 3 + 100 * sin(pi/4) * t - 16 * t.^2; % notice the dot >> plot3(x,y,z);
6.5.7 Plotting functions z=f(x,y)
The plot of a function z = f(x,y) is done by plotting the triples of points (x,y,f(x,y)), just as the plot of the function y=f(x) is the plot of the pairs of points (x,f(x)). To do such a plot, we need to define the values of x and y which is done with meshgrid and then find the corresponding z values. This exactly what we needed to do to plot and plane, and the idea is no different. Here are some examples.Here is the plot of the bell curve
>> temp = -3:.1:3;[x,y]=meshgrid(temp,temp); >> z = (1/sqrt(2*pi)) * exp((x.^2+y.^2)/2); % the bell curve >> surf(x,y,z); % use the surf commandPlot the egg carton f(x,y) = sin(x) * sin(y):
>> temp = -3*pi:.1:3*pi;[x,y]=meshgrid(temp,temp); >> z = sin(x) .* sin(y); % notice the ``dot'' >> surf(x,y,z)Plot the function f(x,y) = cos((x2 + 2y2)/4)
>> temp = -pi:.1:pi; [x,y]=meshgrid(temp,temp); >> z = cos((x.^2 + 2*y.^2)/4); >> surf(x,y,z);
6.5.8 Plotting with csimovie.m
You can use the function csimovie top plot 3d trajectories. Try the help command to find out more information. The file csimovie.m is installed on the CSI network, or can be found here for you to install.7 Finding zeroes
In this section we learn several methods for finding zeroes of a function. A brief note on vocabulary is in order.- If we have an equation, we talk about solutions to the
equation: For example the equation sin x = cos x has solutions
in [0,2p] given by x = p/4 and x=5p/4.
- If we have a function f(x) then a zero of f(x) is a
value x for which f(x) = 0. To relate to a solution, let f(x) =
sin x -cos x. Then the zeroes of f(x) are the
solutions to the equation sin x = cos x
- If we have a polynomial f(x) then the zeroes often get a special name: roots. So, if f(x) = x2 + 5x + 6 then the roots of f(x), (x=-3 or x=-2) are the solutions to f(x) = 0.
7.1 Graphically finding zeroes
Here is an example to illustrate how we can find zeroes of a function using the graphing capabilities of MATLAB.Example: Finding zeroes graphically
Find all solutions of the equation x3 = 20 cos x.
(Notice that this is a non
