Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
97 views

Part 1: Elementary Calculations: MATLAB Tutor

The document provides an introduction to basic MATLAB commands for performing elementary calculations, using variables, plotting functions, and saving your work. It demonstrates how to add, subtract, multiply, divide and take powers in MATLAB. It also shows how to define and use variables, add comments, plot functions by generating lists of x and y values, and save your MATLAB session work to a diary file.

Uploaded by

Ranjit Rajendran
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views

Part 1: Elementary Calculations: MATLAB Tutor

The document provides an introduction to basic MATLAB commands for performing elementary calculations, using variables, plotting functions, and saving your work. It demonstrates how to add, subtract, multiply, divide and take powers in MATLAB. It also shows how to define and use variables, add comments, plot functions by generating lists of x and y values, and save your MATLAB session work to a diary file.

Uploaded by

Ranjit Rajendran
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

MATLAB Tutor

Part 1: Elementary Calculations

To send each command entry instruction to MATLAB for processing, press the
RETURN or ENTER key on your keyboard.

1. In the MATLAB workspace, at the prompt, type

     2 + 3

and then press RETURN or ENTER.


2. Enter

     2 - 3
3. Enter

     2*3
4. Enter

     6/3
5. Enter

     2^3

Now you know how to add, subtract, multiply, divide, and raise a number to a
power in MATLAB – much the same way you do with a calculator or with other
software packages.

The most recent result is always stored in a variable called ans (for ‘answer’).
Only the very latest result is stored there.

6. Enter

     ans

Observe that your last result is still there.


7. Enter

     2*ans

You can compute with the result stored in ans in the same way that you
can with any number.
8. Press the up arrow once, and then press Enter.
9. Press the up arrow several times, and note what happens. You can
recover all your previous commands and re-execute them if you desire.
10. Enter

     sqrt(5)
11. Enter

     pi
12. Enter

     i

You can use the right and left arrows on the keyboard to move right and left to
edit a command line. Thus, you can correct mistakes by recalling a command
with the up arrow and editing to correct it. You can type over a symbol you want
to change or use the backspace key to delete it.

13. Use the up arrow to recover the command sqrt(5). Edit it using the right
and left arrows and compute sqrt(8+pi).
14. Enter

     format long

and then enter

     pi
15. Enter

     format short

and then enter

     pi
16. Enter

     format short e

and ask for the value of pi.


17. Enter

     format rational

and ask for the value of pi.


18. Finally, for real fun, enter

     format hex

and ask for the value of pi.


Unless you especially want to see the rest of your answers displayed in
hexadecimal (base 16) form, change back to

     format short

MATLAB Tutor

Part 2: Comments

Any statement in MATLAB that is preceded by a percent sign % is treated as a


comment -- that is, it is ignored by the MATLAB compiler.

1. Enter

     % Now we will define the coefficients of the polynomial:


     a = 2;
     b = 5;
     c = 6;
2. Enter

     n = 3   % n is the number of roots of the equation.

An entire line may be a comment, or just the second part of a line.

In Part 4 of this tutorial, you will learn how you can save the work you do during a
MATLAB session into a "diary" file. You should include many MATLAB
comments in your work so that later, when you read your diary file, you can see
what you were doing.

MATLAB Tutor

Part 3: Variables

Remember to press Enter or Return after each command.

1. Enter

     x=3
2. Enter

     y=2
3. Enter

     2*x+y

Note that the variable x has been assigned the value 3, and the variable y has
been assigned the value 2, so the algebraic expression you typed was evaluated
using those values, and the result has been stored in the variable ans.

4. Enter

     x
5. Enter

     y

In general, to see what is stored in a variable, just type its name.

6. Enter

     z=5;
7. Enter

     z

Note the effect of the semicolon; use it when you do not want to see your input
echoed. The computer still knows what is stored in the variable z.

8. Enter

     2+x-y*z
9. Enter

     ans
10. Enter

     ans + 3
11. Enter

     2*ans
12. To see what variable names you have used in your current session, enter

     who
13. Enter

     a = 3;
     b = 5;
     c = 1;
     discr = b^2 - 4*a*c;
14. Enter

     discr
15. Enter

     DISCR

Is MATLAB case-sensitive?

There may in fact be times when you want to use the letter a to represent a real
number and the letter A to represent a matrix, and MATLAB will let you do that.
Remember, if you ever forget what variables are in current use, use the who
command. (Or, for more information, use the whos command!)

16. Enter

     sqrt(discr)
17. Enter

     x = (-b + sqrt(discr)) / (2*a)

You will make use of vector variables on many ocassions in MATLAB. A vector
is just a list of numbers. To enter a vector, enclose its components in square
brackets and separate them by commas or blanks. This gives you a "row vector."
which displays horizontally. You can make it into a "column vector" by putting a
single quote mark after it.

18. Enter

     x = [3, -1, 4, 2]


19. Enter

     x'      % Transpose

You can do arithmetic operations on all components of a vector at once. This is


especially important when you want to plot the graph of a function.

20. Enter

     2*x
21. Enter

     x/3

In order to of raise all components of a vector to a power or divide or multiply one


vector by another, you must use the dot operator.

22. Enter

     x^3     % Note error message


23. Enter

     x.^3     % Note the use of the dot


24. Enter

     3.^x
25. Enter

     x/(2+x)
26. Enter

     x./(2+x)     % Note the use of the dot

Make sure you understand what is going on before continuing to the next part of
the tutorial.

MATLAB Tutor

Part 4: Saving your work

If you want to save the work you do in a MATLAB session, you must create a
diary file. This file will contain a complete transcript of everything you type into
the computer, and everything the computer responds. Later, you can edit it with
any word processor.

To start a diary file called ‘Lab1.txt’ on the diskette in drive a, for instance, you
would type

diary a:Lab1.txt
and press Enter. You probably won’t see anything happen, but the computer is
keeping track of your work.

You can suspend saving your work at any time by typing

diary off

Typing diary on will go back to saving your work at the bottom of your previous
diary file. If diary is on when you quit MATLAB, your diary file will be
automatically closed.

When you quit your MATLAB session, the values of all your variables are lost.
Your diary file only keeps a log of what has appeared on your screen, not stored
values of variables. If you want, before you quit MATLAB, you can save the
current values of variables into a file to use in a future session. The following
command would save the values into a file called myfile:

save myfile

The values of all the variables in your workspace will be saved in binary form,
unreadable by humans, into a file called myfile.mat in your working directory. In a
future MATLAB session, to load all these variable values into the new session,
use the command:

load myfile

MATLAB Tutor

Part 5: Graphing Functions

All of the standard mathematical functions, plus many other functions, are
available in MATLAB. Functions operate both on both single numbers and on
vectors. You can use MATLAB just like a calculator.

1. Enter

y = cos(3.5)    % Assumes radians


2. Enter
x = [-2, 4, 1, -1]
z = sin(x)
3. Enter

w = log(1 + abs(x))./atan(x)      % Note the period

The standard method of graphing functions in MATLAB requires you to make


lists (really vectors) of x values and y values and then give the command to plot
the (x,y) pairs. You can get a list of x values covering the range you need by
using a command of the form:
    x = xstart: xincrement: xend .
Below, we plot the built-in function y = exp(x) on the interval from –1 to 2.

4. Enter

x = -1: 0.1: 2
y = exp(x)
plot(x, y)

Usually, we don’t want to print out the x and y lists so we use a semi-colon to
suppress the output.

We can control the graph's color and line style by adding an extra parameter to
the plot command. Choices for colors are 'c' (cyan), 'm' (magenta), 'y' (yellow), 'r'
(red), 'g' (green), 'b' (blue), 'w' (white), and 'k' (black). Line style choices are '-' for
solid (the default), '- -' for dashed, ':' for dotted, and '- .' for dash-dot. Let's make
the graph red and dotted.

5. Enter

x = - 4: 0.5: 3;
y = cos(x);
plot(x, y, 'r:')

MATLAB has marker types '+', 'o', ' * ', and 'x' and the filled marker types 's' for
square, 'd' for diamond, '^' for up triangle, 'v' for down triangle, '<' for right
triangle, '>' for left triangle, 'p' for pentagram, and 'h' for hexagram. If you specify
a marker but not a line style, your graph only has disconnected markers. Here we
plot blue diamonds.

6. Enter

plot(x, y, 'bd')
Using unconnected markers is just what we want in order to produce a scatter-
plot of data points. Rarely do we want such points connected by lines.

7. Enter

x = [1, 2, 4, 5, 7]
y = [10, - 4, 3, 1, 6]
plot(x, y, 'ro')

We can plot more than one graph on a single plot by using the hold on
command to save the old plot and then make another plot the usual way. Below,
we add the line y = - 3*x + 15 to the last scatter-plot.

8. Enter

hold on
x = 1: 0.2: 7;
y = - 3*x + 15;
plot(x, y, 'b')

There are additional commands that allow us to control the "window" of the
graph, add grid lines, put labels on the axes, add a title for the graph, and specify
a legend. We will add these features to our plot.

9. Enter

% Window: 1 < x < 7, - 5 < y < 1


axis( [1, 7, - 5, 11] )
grid on
xlabel( 'x values' )
ylabel( 'y-axis' )
title( 'Plot of y versus x' )
legend( 'data points', 'line')

There is another, sometimes easier, way to make a plot in MATLAB; using the
fplot function. You simply put the name of your function in single quotes. You
can use line markers for the curve like '- +', '- x', '- o', and '- *'. You have no
choice of color and generally have less control over the appearance of the plot.
To find out more about features of fplot, type "help fplot" at the MATLAB prompt.

10. Enter
clf    % clears figure window
fplot('sin(x)', [- 3, 3])
grid on

Experiment with combinations of the commands used for plotting to be sure you
feel comfortable using them.

MATLAB Tutor

Part 6: M-Files and User-defined Functions

A good way to "automatically" execute a sequence of often-used commands


without having to go to the trouble of typing them in each time is to use an m-file.
An m-file is a plain text file that you can create with any text editor. In it, you can
put the same kind of commands that you type in at a MATLAB prompt.

Typing the m-file's name at a prompt simply successively executes the


commands in the file. It is just as if you had typed them in at individual MATLAB
prompts.

1. Use a text editor to create a file that contains the following lines. Save the
file in your working directory under the name tester.m.

d2r = pi/180
a = sin(30*d2r)
b = (1 + a)/4

2. In MATLAB, at the prompt, enter

tester

There will be occasions when you will need to define your own specialized
functions which are not built into MATLAB. You do this by using a special kind of
"function" m-file. As with standard functions like sin(x), a function m-file accepts
input arguments and returns outputs.

An example function m-file is given below. It accepts the input argument x and
returns y = fun(x). Note that the first line contains the key word "function" and
describes inputs and outputs. The output value must be assigned within the
"program" to the variable y which appears before the equals sign on the first line
of the file. The m-file must be given the same name as the function, namely
fun.m.

3. Use a text editor to create a file that contains the following lines. Save in
your working directory under name fun.m.
function y = fun(x)
d2r = pi/180 ;
y = 3*cos(x*d2r) - 1 ;

4. In MATLAB, at the prompt, enter

fun(45)
5. Enter

z = 30
a = fun(z)+ 8

User-defined functions can be plotted as easily as built-in ones. We will use the
plot commands we learned in Part 5 of this Tutorial.

6. Enter

x = -10: 0.5: 20;


y = fun(x);
plot(x, y)
7. Enter

fplot('fun(x)', [- 10, 20], '-o')

You can define functions that take inputs of more than one variable. Output can
likewise be more than one variable. Both input and output variables can be
vectors.

MATLAB Tutor

Part 7: Symbolic Mathematics

If you are using the Student Version of MATLAB, then you have access to the
optional Symbolic Math Toolbox. If you are using a professional (non-student)
version, then you must purchase this toolbox separately. If you do not know
whether your version of MATLAB is equipped with the toolbox or not, try a few of
the following exercises. If they work, you’ve got it. If not, you will have to skip
over any exercise that asks you to perform computations with variables that have
not been assigned numeric values and should be treated as symbols.

MATLAB’s Symbolic Math Toolbox uses Maple, a powerful computer algebra


system, to manipulate and solve symbolic expressions.
1. Whenever you want to use symbolic mathematics, you must use the syms
operator to alert MATLAB that you are using a symbolic variable, and that
it does not have a specific value. Enter

     syms x   % x is a symbolic variable


     f = 3*x^2 - 5*x + 1   % sym expression
     g = x^2 + 2*x   % so is g
     f + g
2. Compare the result of step 1 to the one you get when you enter the
following statements:

     x = 5   % x has a numeric value


     f = 3*x^2 - 5*x + 1
3. MATLAB has a plot command called ezplot that will plot symbolic
functions. Enter

     syms x
     f = 3*x^2 - 5*x + 1
     ezplot(f, [- 3,2])
4. To substitute a number or a symbol into a symbolic expression, use the
subs command. Enter

     subs(f, x, - 2)
     syms q
     subs(f, x, q)
5. Below we declare four symbolic variables at once using the syms
command and solve a quadratic equation using the solve command.
Enter

     syms a b c t   % Create symbolics


     g = a*t^2 + b*t + c
     solve(g, t)   % Solve g = 0 for t

MATLAB Tutor

Part 8: Differentiation

MATLAB can find the derivative of symbolic expressions. Higher derivatives can
also be found easily. These derivatives can be evaluated for arbitary values of
the independent variable.

1. First we declare x to be a symbolic variable and define g to be the function


given by g(x) = x2 cos x.   Enter:

syms x
g = x^2*cos(x)

2. Now enter:

diff(g, x)

Then enter:

diff(g, x, 2)

How would you calculate the third derivative?

3. If you want to calculate the derivative of an expression that you have not
yet entered, just replace g by the expression. For example, enter:

diff(x^3-x^2+2, x)

Now insert a symbolic constant a into the expression.   Enter:

syms a
diff(x^3 - a*x^2 + 2, x)

Then change the final x to an a. That is, enter:

diff(x^3 - a*x^2 + 2, a)

What is the role of the symbol after the comma in the differentiation
expression?

4. Now, suppose you want to evaluate the derivative dg/dx at x = 2.1. Enter:

gp=diff(g, x)

Then enter:

subs(gp, x, 2.1)

Alternatively, you could enter:

subs( diff(g, x), x , 2.1 )

5. Check your understanding so far by using MATLAB to calculate the


second derivative of tan(x6 - 3x + 5) at x = 3/2.
(The value is approximately  - 4521.)
MATLAB Tutor

Part 9: Integration

MATLAB can find both an indefinite integral (i.e., antiderivative) and a definite
integral of a symbolic expression. That assumes an elementary antiderivative
exists. If not, MATLAB can compute a very accurate numerical approximation to
the definite integral.

1. First we calculate indefinite integrals. Before doing anything, we must


declare x to be a symbolic variable.   Enter:

syms x

Then enter

int(x*sin(x), x)

Check that the result is an antiderivative of x sin(x) by entering:

diff(ans, x)

2. Introduce another symbolic variable a to investigate how MATLAB deals


with more than one symbolic variable in integration. Enter:

syms a

Then enter

int(a*sin(x), x)

Now enter

int(a*sin(x), a)

What is the role of the variable following the comma?

3. Now try to find an antiderivative for sin ( x5 + x3 ).

MATLAB does not know an antiderivative of this function that can be


defined in terms of functions known to MATLAB. On the other hand, enter:

int(sin(x^2), x)

The Fresnel S function is known to MATLAB, but probably not to you.


However, you can check by differentiation that the expression is an
antiderivative.

4. Next we calculate definite integrals. To integrate x sin(x) over the interval


[0,pi/2], enter:

int(x*sin(x), x, 0, pi/2)

5. Now try this method on the integral of sin ( x5 + x3 ) over the interval
[0,pi/2].

MATLAB still doesn't know an antiderivative for this function. To obtain a


numerical estimate, enter:

double( int(sin(x^5 + x^3), x, 0, pi/2) )

6. If you know that all you want is a numerical estimate, you can use
MATLAB's numerical integrator called quad8. No symbolics are involved.
Enter:

quad8( inline('sin(x^5+x^3)'), 0, pi/2 )

Numerical integration also works with user-defined functions in m-files.


Symbolic integration doesn't. If you still have the m-file called fun.m that
you created in Part 6 of this Tutorial, enter:

quad8('fun', 0, pi/2 )

The significance of using the quad8 function is that MATLAB does not try
to find a symbolic solution before starting on the numerical estimate.

7. Use MATLAB to find the exact value of each of the following integrals.
(Type inf for the infinity symbol.)
o The integral of 1/(1+x2) from 0 to 1,
o The integral of 1/(1+x2) from 0 to Infinity,
o The integral of 1/(1+x4) from 0 to Infinity.

MATLAB Tutor

Part 10: Getting Help

MATLAB has an extensive collection of help messages. If you know the name of
a command, you can find the proper syntax for the command and examples of its
use by typing help command_name. That's assuming you know the command's
name.
1. The commands are stored in various MATLAB libraries. Let's get a list.
Enter:

     help
2. Suppose you want to see if MATLAB has the elementary function
arctangent, the inverse tangent function. Look down the list of libraries.
There seems to be a likely candidate there. You can identify the directory
by using only the last part of the filename. Enter:

     help elfun
3. Sure enough, the list has a function called atan on it. Enter:

     help atan

Practice finding other MATLAB commands and getting help on their use.

MATLAB Tutor

Part 11: Using MATLAB with the CCP Modules

MATLAB m-files designed for use in conjunction with the Connected Curriculum
Project modules are available for downloading to your computer.

When you click on the MATLAB icon that appears on the table-of-contents page
of a module, you will get instructions about how to download a "package" of m-
files that are coordinated with the module. For example, for the module named
Numerical Solutions of Differential Equations, there are seven m-files in the
package, namely, numdiff1.m through numdiff5.m, dfun.m, and slpfield.m.

1. Click on the MATLAB icon below and you will see the page of instructions for
downloading and uncompressing the package of m-files for the Numerical
Solutions of Differential Equations module. Go ahead and download the
appropriate package file.

After you have downloaded and uncompressed the package of m-files, then to
use the instructions in the file numdiff1.m, for example, all you have to do is type:
numdiff1 at the MATLAB prompt and press Enter. The instructions will appear in
your MATLAB window. That assumes, of course, that MATLAB knows which file
on your computer system contains numdiff1.m.

There are two ways that you can tell MATLAB where to find the numdiff1.m file.
You can either (1) make sure the file is in your working directory, or (2) add the
name of the file that contains numdiff1.m to MATLAB’s search path.

You can make sure you are in the directory containing the m-files you need
before you even start-up your MATLAB session. You can also change your
working directory while you are in MATLAB as we now demonstrate.

2. If you are in MATLAB, to find out what your working directory is, enter:

pwd

3. To see a list of all the files in your working directory, enter:

dir

You can navigate through your directories to find the one containing numdiff1.m
by using the "cd" command (which stands for "change directory").

4. To go up one in the directory structure, enter:

cd ..    %a space followed by two periods

5. Pick the subdirectory you want to go to in the subdirectory list inside the
directory. To go there, enter:

cd sub_name    %change "sub_name"

An alternative way to tell MATLAB where to find your m-files, especially if they
are in two different directories, is to add the directory or directories containing
these m-files to the search path.

6. To find out what MATLAB’s current search path is, enter:

path

You can add the directories mydir1, mydir2, etc. to the old path with the
command: addpath mydir1 mydir2 etc.

Unfortunately, when you quit your current MATLAB session, your additions to the
path are "forgotten." If you always start your new MATLAB sessions from the
same working directory, you can use your text editor to create an m-file titled
startup.m in that directory which MATLAB automatically executes when it starts.
In that m-file, put the line addpath mydir1 mydir2 etc.

In MATLAB, if you know the name of a command, you can get information about
it by entering: help command_name at a prompt. If you enter: help path or
help addpath you will find more detailed instructions on the use of these
commands as well as examples of adding file names to paths for a variety of
computer systems including Unix, Windows/DOS, and Macintosh.

MATLAB Tutor

Part 12: Symbolic solution of differential equations

In this part we explore MATLAB's ability to solve the logistic equation

dy/dt = y (1 - y)

and to check the solution. Then we will adapt the solution procedure to an initial
value problem with this same differential equation. In the next part, we will relate
these algebraic calculations to the geometry of direction fields.

1. First declare the variable t as symbolic and give the differential equation a
name by entering:

syms t
DE1 = ' Dy = y*(1 - y) '

Then ask MATLAB to solve the differential equation by entering:

ysol = dsolve(DE1)
pretty(ysol)     % Gives nice format

Note that MATLAB uses C1 to represent an arbitrary constant.

2. Differentiate your solution expression with respect to t to get an explicit


expression for dy/dt. You can can differentiate ysol and simplify the result
by using:

dysol = simple( diff(ysol) )


pretty(dysol)     % Gives nice format

Then use your solution expression ysol to find an explicit formula in t for
y(1 - y). Is this formula the same as the one for dy/dt? You may want to
simplify the output before you try to answer this.
3. Now we add the initial condition y(0) = 1/10 to determine a single solution
of the differential equation. To tell MATLAB to solve the initial value
problem, put both parts of the problem -- the differential equation and the
initial condition -- into dsolve. Enter:

h = dsolve( DE1, ' y(0) = 1/10 ' )


pretty(h)     % Gives nice format

4. What do you have to do to check the answer from the preceding


step? Have you done it already? If not, can you get the checking
technique from what you did in Step 2?

To substitute t = 0 into the solution function h, enter:

subs(h, t, 0)

We will use our solution function h for further computations in Part


13, which follows next.

MATLAB Tutor

Part 13: Direction fields

1. MATLAB does not have a built-in command to plot direction fields. An m-


file that provides a function for this purpose called "slpfield" is provided for
every module that needs direction fields.

If you downloaded the package of m-files in Part 11 of this tutorial, this


function is available to you, provided the file slpfield.m is in your working
directory or on MATLAB's path. If you have not yet downloaded the
package, go back to Part 11 and do it now.

2. In order to make the plot of the direction field, the "slpfield" function must
be provided a function called "dfun" which gives the right hand side of the
differential equation.

Use a text editor to edit the file dfun.m (provided in the same package as
slpfield.m) so that the right-hand-side function is y.*(1-y). (The period after
the y is important.)
3. Assuming you have the correct dfun.m file, we can now plot the vector
field on the interval -2 < t < 2 and -0.5 < y < 2. Enter:

slpfield(-2, 2, -0.5, 2)
hold on     %holds the plot

4. Now plot the function h from Part 12 on top of the slope field plot. We use
the same limits on t. Enter:

ezplot( h, [-2,2] )
axis( [-2, 2, -0.5, 2] )

Does this solution look like it fits the direction field?

5. Adjust the horizontal ranges and redraw the direction field and the solution
plot so that you can see the solution function h approach equilibrium. If
necessary, enlarge the picture so you can see more detail. Are you
convinced that the symbolic solution h fits the direction field?

6. Edit the dfun.m file in order to generate direction fields over appropriate
ranges of the variables for the following differential equations:

o dy/dt = y2
o dy/dt = ty + t

You might also like