Math 442 - Introduction to MATLAB 1 Introduction Glenn Lahodny Jr.

advertisement
Math 442 - Introduction to MATLAB
Glenn Lahodny Jr.
1
Introduction
In this course, we will make frequent use of the MathWorks software package MATLAB.
1.1
Starting MATLAB
Let us begin by starting MATLAB. There are several ways which you can access MATLAB
at Texas A&M University.
1.1.1
How to Start MATLAB in a Calclab Room
The easiest way to access MATLAB is in a calclab room (e.g. BLOC 122).
1. Log in to your calclab account using your NetID and password.
2. Click Start, Mathematics, Matlab.
A schedule of the calclab rooms can be found at http://calclab.math.tamu.edu/.
1.1.2
How to Start MATLAB in an Open Access Computer Lab
You can access your calclab account from any open access lab with the NX client.
1. Log in with your NetID and password.
2. Click Start, All Programs, Communications, NX Client for Windows.
3. Choose calclab1.math.tamu.edu as your host.
In setting up this connection you can create an icon on the desktop that will automatically
connect to your calclab account.
1.1.3
How to Access MATLAB from Home
A copy of MATLAB 2014-2015 for Windows is available for free at http://software.tamu.edu.
You can also access MATLAB using the Texas A&M Virtual Online Access Library (VOAL).
1. Open Internet Explorer and go to https://voal.tamu.edu.
2. Allow the required add-on to run.
3. Sign in using your credentials.
4. Click VOAL1 (or other depending on the time of day) and then OK.
5. Click Start, All Programs, Applications, MATLAB 2012a (or current version).
1
1.2
The MATLAB Interface
The default MATLAB screen is divided into four windows.
1. Command Window (Where calculations are carried out)
2. Current Folder (Displays the current directory)
3. Workspace (Displays variables and information about variables)
4. Command History (Displays commands typed in current and previous sessions)
1.3
Basic Calculations in MATLAB
The following is a list of algebraic operations used in MATLAB:
Addition Subtraction Multiplication Division Exponentiation
+
*
/
^
The following is a list of some elementary quantities and functions used in MATLAB:
√π
−1
|x|
√
x
ex
ln(x)
sin(x)
cos(x)
tan(x)
sin−1 (x)
cos−1 (x)
tan−1 (x)
pi
i
abs(x)
sqrt(x)
exp(x)
log(x)
sin(x)
cos(x)
tan(x)
asin(x)
acos(x)
atan(x)
A full list of elementary functions can be found in the MATLAB help menu.
Example: Use MATLAB to evaluate the following expressions.
(a) |2π 3 − 5|
√
(b) π 2 − 1
(c) e3 ln(2)
2 π
(d) sin
+ sec(3)
3
2
1.4
Formatting Numerical Output in MATLAB
By default, MATLAB displays all numerical output using four decimal places. If further
accuracy is needed, then additional decimal places can be displayed.
Enter the following commands in the command window:
>> 1+1/2
>> format long
>> 1+1/2
>> format rat
>> 1+1/2
>> format short
>> 1+1/2
1.5
Defining Variables in MATLAB
Variables can be assigned particular values to be used in later calculations. All variables
which have been defined, along with their values, are displayed in the workspace window.
Enter the following commands in the command window:
>> x=5;
>> y=x+15;
>> z=sin(y)
>> v=1:50;
>> who
>> whos
Enter the following commands into the command window:
>> clear z
>> clear
1.6
Creating a Diary File
In this course, you may be required to turn in a log of MATLAB commands you entered
along with the MATLAB output. This can be done using the diary command.
Enter the following commands into the command window:
>> diary Script1.txt
>> % Your Name
>> % MATH 442 - Mathematical Modeling
>>
>> x=1;
>> atan(x)
>> diary off
3
This creates a text file Script1.txt in the current directory (which can be identified in the
current directory window) which records the commands that follow, along with MATLAB’s
responses, until the command diary off is entered.
To print the text file Script.txt, follow the xprint instructions posted in the Blocker lab. That
is, open a terminal window by clicking the terminal icon from the bottom of your screen and
enter the following command:
xprint -d blocker Script1.txt
You will be prompted to give your NetID and password. The file will be printed in Blocker
130.
1.7
Getting Help in MATLAB
The command help is extremely useful when working in MATLAB. Simply enter this command in the command window to access help on many MATLAB commands. For help on
a particular topic, such as the differentiation command diff, enter the command help diff in
the command window. Additionally, there is help available from the MathWorks website
available at http://www.mathworks.com/help/matlab/.
4
2
Vectors and Matrices
2.1
Vectors
Column and row vectors can be created in MATLAB by using square brackets. To create a
column vector, enclose a set of numbers in square brackets and use a semicolon to delimit the
numbers. For example, to create a column vector with three elements, enter the command:
>> x=[1;2;3]
To create a row vector, enclose a set of numbers in square brackets and use a space or comma
to delimit the numbers:
>> v=[1 2 3]
>> w=[4,5,6]
2.2
Vectors with Uniformly Spaced Elements
It is often useful to create a vector with elements that are uniformly spaced by some increment, say p. To create a vector ~x with uniformly spaced elements where x1 is the first
element and xn is the final element, we use the syntax
x = [x1 : p : xn ].
To create a list of even numbers from 0 to 10, enter the command:
>> x=[0:2:10]
It is also possible to create a vector of uniformly spaced elements with a negative increment.
To create a list of numbers from 100 to 80 decreasing by 5, enter the command:
>> z=[100:-5:80]
The linspace command can also be used to create a vector with uniformly spaced elements.
In particular, the command linspace(a,b,n) creates a vector of n regularly spaced elements
between a and b. As an example, enter the following commands:
>> linspace(1,10,10)
>> linspace(1,10,4)
This technique will be used for plotting the graph of a function. For example, we can create
a set of points on the graph of the function y = ex using the commands:
>> x=[0:0.1:1];
>> y=exp(x);
5
2.3
Characterizing a Vector
The length command returns the number of elements in a vector.
>>
>>
>>
>>
A=[1 2 3 4];
B=[1 2];
length(A)
length(B)
The max and min commands return the maximum and minimum elements of a vector.
>> A=[1 -2 3 -4];
>> max(A)
>> min(A)
2.4
Vector Dot and Cross Products
The commands dot and cross return the dot and cross product of two vectors, respectively.
>>
>>
>>
>>
a=[1 2 3];
b=[2 3 4];
dot(a,b)
cross(a,b)
The dot product can be used to compute the magnitude of a vector.
>> M=sqrt(dot(a,a))
2.5
Matrices
To create a matrix in MATLAB, we enter the elements of each row delimited by a space,
and use semicolons to mark the end of each row.
To enter the matrices
A=
1 2
3 4
and


1 2 3
B = 4 5 6 ,
7 8 9
we use the following commands:
>> A=[1 2; 3 4]
>> B=[1 2 3; 4 5 6; 7 8 9]
There are commands in MATLAB which make creating certain types of matrices easier.
6
As an example, enter the following in the command window:
>>
>>
>>
>>
zeros(2)
zeros(2,3)
ones(2)
ones(3,2)
In some cases, it is beneficial to refer to a particular entry, column, or row of a matrix. If A
is a matrix, the command A(m,n) returns the entry in the mth row and nth column of A.
The command A(1,:) returns the first row of matrix A. In particular, the colon represents
all columns that appear. Similarly, the command A(:,2) returns the second column of matrix
A. Again, the colon represents all rows that appear.
As an example, enter the following in the command window:
>>
>>
>>
>>
2.6
C=[1 2 3; 3 2 1];
C(2,3)
C(3,:)
C(:,1)
Basic Operations with Vectors and Matrices
Basic operations with vectors and matrices can be performed by referencing the variable
used to create them.
Scalar multiplication can be performed as follows:
>> x=[1 2 3];
>> c=2;
>> y=c*x
Addition and subtraction are performed as follows.
>>
>>
>>
>>
A=[1 2 3];
B=[4 5 6];
C=A+B
D=A-B
Matrix multiplication and exponentiation are performed as follows.
>>
>>
>>
>>
A=ones(2);
B=[1 2; 3 4];
A*B
B∧2
7
Componentwise multiplication and exponentiation are performed by using the “dot” notation for the commands .* or .^.
>> A.*B
>> B.∧2
Notice the difference in the expressions for A*B and A.*B.
The transpose of a matrix A can be computed using the command ’.
>> X=[1 2 3; 1 1 1]
>> X’
The command A/B evaluates the expression AB −1 , while the command A./B performs componentwise division of A and B.
>> A/B
>> A./B
To evaluate the determinant of a square matrix, we use the command det. Provided that a
square matrix is nonsingular, we can evaluate its inverse using the command inv.
>> det(A)
>> inv(A)
The eigenvalues of a square matrix can be computed using the command eigs.
>> eigs(A)
8
3
Plotting and Graphics
3.1
3.1.1
Basic Plotting
The Plot Command
To plot a function in MATLAB, we use the plot command.
Example: Plot the function y = cos(x) over the domain 0 ≤ x ≤ 10.
First we define the domain of interest and desired step size, say 0.1.
>> x=0:0.1:10;
Next we define the function we want to plot.
>> y=cos(x);
To plot the function, we use the plot command.
>> plot(x,y)
1
0.8
0.6
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
2
4
6
8
10
To label the axes of a plot, we use the xlabel and ylabel commands.
Enter the following commands in the command window:
>> xlabel(’x’)
>> ylabel(’cos(x)’)
To add a title to a plot, we use the title command.
Enter the following command into the command window:
>> title(’Cosine Plot’)
9
Cosine Plot
1
0.8
0.6
0.4
cos(x)
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
2
4
6
8
10
x
3.1.2
The Ezplot Command
Suppose we want to plot f (t) = e−t sin(t) for 0 ≤ t ≤ 4. Following the usual procedure:
>> t=0:0.01:4;
>> f=exp(-t)*sin(t);
However this gives the error
Inner matrix dimensions must agree.
Since exp(-t) and sin(t) are row vectors of the same size, they cannot be multiplied using
matrix multiplication. How do we get around this error?
One way is to use the ezplot command which defines the function and its domain in one
command:
>> ezplot(’exp(-t)*sin(t)’,[0,4])
>> xlabel(’t’)
>> ylabel(’f(t)’)
0.35
0.3
0.25
f(t)
0.2
0.15
0.1
0.05
0
-0.05
0
0.5
1
1.5
2
t
10
2.5
3
3.5
4
Alternatively, we could use the .* command for componentwise multiplication of vectors.
That is:
>>
>>
>>
>>
>>
3.2
t=0:0.01:4;
f=exp(-t).*sin(t);
plot(t,f)
xlabel(’t’)
ylabel(’f(t)’)
Multiple Functions on One Plot
In many cases, it is necessary to plot multiple functions on a single graph.
3.2.1
Plotting Multiple Functions
To plot multiple functions on a single graph, we use the syntax plot(x,f(x),x,g(x)).
Example: Suppose we want to plot the functions f (t) = e−t and g(t) = e−2t over 0 ≤ t ≤ 5.
>>
>>
>>
>>
>>
>>
>>
t=0:0.01:5;
f=exp(-t);
g=exp(-2*t);
plot(t,f,t,g)
xlabel(’t’)
ylabel(’f(t), g(t)’)
title(’Multiplot’)
Multiplot
1
0.9
0.8
0.7
f(t), g(t)
0.6
0.5
0.4
0.3
0.2
0.1
0
0
1
2
3
4
5
t
Note that MATLAB uses two different colors to differentiate between the two curves.
11
3.2.2
Setting Colors and Line Style
The color and line style of each curve can be manually selected using the plot command.
The color is specified in the plot command immediately after the function is specified by
enclosing the appropriate letter assigned to each color in single quotes. Similarly, the line
style is specified by enclosing the appropriate symbol assigned to each line style in single
quotes.
Example: Suppose we want to plot the functions f (x) = sin(x) and g(x) = cos(x) over
0 ≤ x ≤ 5. Additionally, we would like the graph of f to be a solid red line and the graph
of g to be a dashed blue line. Starting in the usual way, we have:
>>
>>
>>
>>
>>
>>
x=0:0.01:5;
f=sin(x);
g=cos(x);
plot(x,f,’r’,x,g,’b--’)
xlabel(’x’)
ylabel(’sin(x), cos(x)’)
1
0.8
0.6
sin(x), cos(x)
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
x
The following is a list of some colors and line styles available in MATLAB.
Color/Line Style Specifier
Black
k
Blue
b
Red
r
Green
g
Yellow
y
Cyan
c
Magenta
m
Solid Line
Dashed Line
-Dotted Line
:
Dash-Dotted Line
-.
A full list of available colors and line styles can be found in the MATLAB help menu.
12
3.2.3
Adding Legends
A legend can be added to the plot of multiple functions using the legend command.
To add a legend to our previous plot of f (x) = sin(x) and g(x) = cos(x), enter the command:
>> legend(sin(x),cos(x))
1
sin(x)
cos(x)
0.8
0.6
sin(x), cos(x)
0.4
0.2
0
-0.2
-0.4
-0.6
-0.8
-1
0
1
2
3
4
5
x
3.3
Multiple Plots
To create multiple plots in one figure, we use the command subplot. In particular, the syntax
subplot(m,n,k) creates an m × n array of graphs with the current plot in position k (ordered
left to right and top to bottom).
Example: Consider the parametric curve defined by x(t) = sin(t), y(t) = t cos(t) for 0 ≤ t ≤
2π. Suppose we want to plot both x(t) and y(t) as functions of t and also want to plot the
curve in the xy-plane.
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
>>
t=0:0.01:2*pi;
x=sin(t);
y=t.*cos(t);
subplot(1,2,1)
plot(t,x,’r’,t,y,’b’)
xlabel(’t’)
ylabel(’x(t), y(t)’)
legend(’x(t)’,’y(t)’)
subplot(1,2,2)
plot(x,y)
xlabel(’x’) ylabel(’y’)
13
8
8
x(t)
y(t)
6
4
4
2
2
0
0
y
x(t), y(t)
6
-2
-2
-4
-4
-6
-6
-8
-8
-10
-10
0
5
10
-1
t
3.4
0
1
x
Saving and Printing Plots
In this course, it will be beneficial to save plots as both MATLAB figures (.fig) and Encapsulated Postscript (.eps) files. To print a plot from a calclab room, we use the xprint
command.
14
4
Symbolic Calculations in MATLAB
4.1
Defining Symbolic Variables and Expressions
Symbolic variables can be defined in MATLAB using the syms command. The symbolic
variables we have defined appear in the Workspace window.
Example: Suppose we want to symbolically define the quadratic equation y = ax2 + bx + c.
>> syms a b c x
>> y=a*x∧2+b*x+c;
Symbolic variables can be cleared using the clear command. In particular, if x is defined as a
symbolic variable, then the command clear x will delete the variable x. To clear all variables
from the Workspace window at once, enter the command clear.
4.2
Formatting Symbolic Expressions
There are a variety of ways to format symbolic expressions in MATLAB.
4.2.1
The Expand Command
The expand command carries out products by distributing. It can also be used to expand
trigonometric, exponential, and logarithmic expressions.
Example: Expand the expression y = (x + 2)(x − 4).
>> syms x
>> y=(x+2)*(x-4);
>> expand(y)
Example: Expand the expression z = ex+y .
>> syms x y
>> z=exp(x+y);
>> expand(z)
Example: Expand the expression f (x, y) = sin(x + y).
>> syms x y
>> f=sin(x+y);
>> expand(f)
15
4.2.2
The Collect Command
The collect command groups all terms that have a variable to the same power.
Example: Suppose we want to group the equation y = x(x2 + sin x)(x3 + ex ) by powers of x.
>> syms x
>> y=x*(x∧2+sin(x))*(x∧3+exp(x));
>> collect(y)
Example: Suppose we want to group the expression x2 y + xy − x2 − 2x by powers of x.
>> syms x y
>> collect(x∧2y+x*y-x∧2-2*x,x)
4.2.3
The Factor Command
The factor command is used to factor polynomials and other expressions.
Example: Suppose we want to factor the expression
(x4 − 1) = (x2 + 1)(x + 1)(x − 1).
>> syms x
>> factor(x∧4-1)
4.2.4
The Simplify Command
The simplify command is used to rewrite a symbolic expression with the least number of
characters.
Example: Simplify the expression y =
x4 − 81
.
x2 − 9
>> syms x
>> y=(x∧4-81)/(x∧2-9);
>> simplify(y)
Example: Use the simplify command to simplify the expression
√
f (x, y) = ec ln(
>> syms x y c
>> f=exp(c*log(sqrt(x∧2+y∧2)));
>> simplify(f)
16
x2 +y 2 )
.
Example: Use the simplify command to show that sin2 x + cos2 x = 1.
>> syms x
>> simplify(sin(x)∧2+cos(x)∧2)
4.3
Solving Algebraic Equations
To solve an algebraic equation in MATLAB, we use the solve command.
Example: Suppose we want to solve the equation
x2 − 8x + 15 = 0.
>> syms x
>> y=x∧2-8*x+15;
>> solve(y)
MATLAB can also solve equations symbolically.
Example: Suppose we want to solve the general quadratic equation
ax2 + bx + c = 0.
>> syms x a b c
>> y=a*x∧2+b*x+c;
>> solve(y)
To solve an equation for a specific variable, we use the syntax solve(eqn,var).
Example: Suppose we want to solve the following equation for the variable y
ex y + cos(x) = 1.
>> syms x y
>> solve(exp(x)*y+cos(x)-1,y)
It is not necessary to define symbolic variables to solve an equation. We can simply use the
syntax solve(’eqn’).
Example: Solve the equation x2 − 6x − 12 = 0.
>> solve(’x∧2-6*x-12’)
17
The solve command can also be used to solve systems of equations.
Example: Suppose we want to solve the following system of equations
5x + 4y = 3
x − 6y = 2.
To solve the system, we use the command.
>> s=solve(’5*x+4*y=3’,’x-6*y=2’)
To get the values of x and y, we use a “dot” notation.
>> x=s.x
>> y=s.y
This method can be used with larger systems as well.
4.4
Numerical Evaluation of Symbolic Expressions
In some cases, it is useful to evaluate a symbolic expression as a numerical value.
4.4.1
The Eval and Double Commands
To express a symbolic expression as a numerical value, we use the eval or double command.
Example: Solve the equation x3 + 2x − 1 = 0 and evaluate the result numerically.
>> s=solve(’x∧3+2*x-1’)
>> eval(s)
>> double(s)
4.4.2
The Subs Command
To substitute a particular value for a symbolic variable into a symbolic expression, we use
the subs command.
Example: Suppose we want to symbolically define the function f (t) = eat and evaluate this
function for t = 0, 1, 2, . . ..
>>
>>
>>
>>
>>
syms a t
f=exp(a*t);
subs(f,t,0)
subs(f,t,1)
subs(f,t,2)
18
Multiple substitutions can be made at the same time.
Example: Suppose we want to symbolically define the function f (x, y) = sin(x) + cos(y) and
evaluate this function for x = 1 and y = 2.
>> syms x y
>> f=sin(x)+cos(y);
>> subs(f,{x,y},{1,2})
19
5
Basic Calculus in MATLAB
5.1
Limits
Limits can be calculated in MATLAB by using the limit command. To compute limits of
the form lim f (x), we use the syntax limit(f,a).
x→a
Example: Find the limit of f (x) =
√
x3 + 1 as x approaches 2.
>> syms x
>> f=sqrt(x∧3+1);
>> limit(f,2)
To compute limits of the form lim f (x), we use the syntax limit(f,inf ) or limit(f,-inf ).
x→±∞
Example: Evaluate lim
√
x→∞
x2 + x − x .
>> syms x
>> f=sqrt(x∧2+x)-x;
>> limit(g,inf)
√
Example: Evaluate lim
x→−∞
4x2 − x + 1
.
x+7
>> syms x
>> f=(4*x∧2+1)/(x+7);
>> limit(f,-inf)
To compute one-sided limits, we use the syntax limit(f,x,a,’left’) or limit(f,x,a,’right’).
x
does not exist.
x→0 |x|
Example: Show that lim
>> syms x
>> f=x/abs(x);
>> L=limit(f,x,0,’left’)
>> R=limit(f,x,0,’right’)
Since L 6= R, the limit does not exist.
20
5.2
Derivatives
Derivatives can be computed using the diff command. To find the derivative of a function
of one variable f (x), we use the syntax diff(f ).
Example: Find the derivative of f (x) = sin(5x).
>> syms x
>> f=sin(5*x);
>> diff(f)
To compute higher derivatives of a function, f (n) (x), we use the syntax diff(f,n).
Example: Find the second derivative of f (t) = te−3t .
>> syms t
>> f=t*exp(-3*t);
>> diff(f,2)
To find the derivative of a function of two or more variables f (x, y), we use the syntax
diff(f,x) or diff(f,y).
Example: Find the first and second-order partial derivatives of g(x, y) = sin(xy) + ex+y .
>>
>>
>>
>>
>>
>>
>>
>>
syms x y
g=sin(x*y)+exp(x+y)
gx=diff(g,x)
gy=diff(g,y)
gxx=diff(gx,x)
gyy=diff(gy,y)
gxy=diff(gx,y)
gyx=diff(gy,x)
21
5.3
Integration
Integrals
R can be computed using the int command. To evaluate indefinite integrals of the
form f (x)dx, we use the syntax int(f ).
Z
Example: Evaluate
ln xdx.
>> syms x
>> f=log(x);
>> int(f)
b
Z
f (x)dx, we use the syntax int(f,a,b).
To evaluate definite integrals of the form
a
Z
4
| sin(x) + x|dx.
Example: Evaluate
1
>> syms x
>> f=abs(sin(x)+x);
>> int(f,1,4)
In some cases, we need to tell MATLAB to integrate with respect to a particular variable.
This can be done using the syntax int(f,x).
Z
Example: Evaluate
>>
>>
>>
>>
Z
2x sec(y)dx and
2x sec(y)dy.
syms x y
f=2*x*sec(y)
int(f,x)
int(f,y)
Z bZ
To evaluate multiple integrals such as
d
f (x, y)dydx, we simply nest the int command.
a
c
That is, we use the syntax int(int(f,y,c,d),a,b).
Z
2
Z
Example: Evaluate
1
sin(x)
exy dydx.
0
>> syms x y
>> int(int(f,y,0,sin(x)),1,2)
22
5.4
Sums and Products
Sums can be computed using the sum command.
Example: Evaluate the sum
5
X
k.
k=1
>> a=1:5;
>> sum(a)
Products can be evaluated using the prod command.
Example: Evaluate the product
10
Y
ln(k).
k=1
>> a=1:10;
>> prod(log(a))
To evaluate symbolic sums, we use the symsum command.
Example: Evaluate the sum
n X
1
k=1
1
−
k k+1
>> syms k n
>> symsum(1/k-1/(k+1),1,n)
23
=1−
1
.
n+1
6
M-Files
The ability to write M-files is necessary for this course.
6.1
Script M-Files
A script M-file is a text file containing a list of MATLAB commands. To create an M-file,
simply click the “New Script” icon in the upper left corner of the MATLAB window. A new
window will appear with MATLAB’s default editor.
Let us write a script M-file to plot the function f (x) = sin(x) on the interval [−2π, 2π]. In
the editor window, enter the following commands:
% Your Name
% Math 442 - Mathematical Modeling
x=-2*pi:0.01:2*pi;
f=sin(x);
plot(x,f)
To save this file, click the “Save” icon in the upper left corner of the MATLAB window and
choose “Save As”. Save your M-file as SinePlot.m. To run this script M-file, click the “Run”
icon (looks like a green arrow) at the top of the MATLAB window. MATLAB goes through
your M-file line by line and executes each command.
6.2
Function M-Files
A function M-file is used to perform operations with a function. This typically involves
inputing some variable or variables which are processed by the M-file and some output is
returned. As before, click the “New Script” icon in the upper left corner of the MATLAB
window. A new window will appear with MATLAB’s default editor.
Let us write a function M-file to find the derivative of f (x) = cos(x) at a given value of
x ∈ R. In the editor window, enter the following commands:
% Your Name
% Math 442 - Mathematical Modeling
function CosineDiff(n)
syms x
f=cos(x);
f1=diff(f,x);
subs(f1,x,n)
24
Every function M-file begins with the function command, and the input is placed in parentheses after the name of the function M-file. To save this file, click the “Save” icon in
the upper left corner of the MATLAB window and choose “Save As”. Save your M-file as
CosineDiff.m. For every function M-file, the file name must be the same as the name of the
function. To run this function M-file, enter the following command in the command window:
>> CosineDiff(0)
The function M-file takes the input n = 0, computes the derivative of cos(x) at x = 0, and
returns the answer in the command window.
Function M-files can also take several inputs at once using the syntax
function Name(x,y,z,...).
Z
Let us write a function M-file to evaluate the definite integral
b
cos(x)dx for given values
a
of a and b. Open a new editor window and enter the following commands:
% Your Name
% Math 442 - Mathematical Modeling
function CosineInt(a,b)
syms x
f=cos(x);
int(f,a,b)
Z
2π
To evaluate the integral
cos(x)dx, enter the following command in the command window:
0
>> CosineInt(0,2*pi)
25
7
Programming in MATLAB
It is possible to create your own programs in MATLAB using an M-file. If you are familiar
with C or C++, you will find programming in MATLAB to be similar.
7.1
7.1.1
Loops
The For Loop
A for loop can be used to repeat a sequence of calculations a predetermined number of times.
Let us write a program which uses a for loop to compute the sum of the first n integers.
Start by opening a new script M-file and entering the following commands.
% Your Name
% Math 442 - Mathematical Modeling
% Computes the sum of the first n integers.
% Sets the final integer value.
n=10;
% Sets the initial value of the sum.
s=0;
% Repeats the calculation s=s+1 for j=1 to j=n.
for j=1:n
s=s+j;
end
% Displays the sum in the command window.
Sum=s
Save this script M-file as IntegerSum.m and run the script to see your final answer.
The index of the for loop can be set to something other than 1. For example, the syntax for
k=2:2:100 counts from 2 to 100 by increments of 2.
7.1.2
The While Loop
A while loop can be used to repeat a sequence of calculations until some criterion is no longer
satisfied.
Let us write a program which uses a while loop to list the integers from 1 to n. Open a new
script M-file and enter the following commands.
26
% Your Name
% Math 442 - Mathematical Modeling
% Lists the first n integers.
% Sets the final integer value.
n=10;
% Sets the initial value.
x=0;
% Repeats the calculation x=x+1 while x<n.
while x<n
x=x+1
end
Save this script M-file as IntegerList.m and run the script to view the output.
7.2
Branching
Branching refers to a program performing different operations for different cases.
7.2.1
If-Else Statements
The most standard way to perform branching is using an if-else statement.
Consider the following example:
if x<y
z=1;
elseif x>y
z=2;
else
z=3;
end
If x < y, then the variable z is assigned the value 1. Similarly, if x > y, then z = 2, and if
x = y, then z = 3.
7.2.2
Switch Statements
A switch statement takes a variable, say x, and performs different operations depending on
the value of that variable.
27
Consider the following example:
switch x
case 1
y=1;
case 3
y=2;
case 5
y=3;
end
If x = 1, then the variable y is assigned the value 1. Similarly, if x = 3, then y = 2 and if
x = 5, then y = 2.
References
1. P. Howard, MATLAB 7.8 Basics. http://www.math.tamu.edu/ phoward/
2. D. McMahon, MATLAB DeMYSTiFieD, McGraw Hill, 2007.
28
Download