week1demo_filled
week1demo_filled
This week, we will introduce the basics of MATLAB. It is important to have some fundamentals of syntax and
good coding practice solidifed before we begin to solve ODEs numerically.
Defining variables
MATLAB is a powerful tool used by mathematicians, engineers, physicists, etc. to solve a wide away of
quantitiative problems. The way you define variables and use them is somewhat intuitive. Let's start by
defining a variable , and let's see what happens if we square c, and assign the result to variable d.
c = 3
c = 3
d = c^2
d = 9
These quantities are scalars. We will also work very often with vectors, which in many cases simply represent
individual points uniformly selected over an interval. For example, let us create a vector-valued quantity x to be
a vector with 100 evenly-spaced points between -5 and 5.
x = linspace(-5,5)
x = 1×100
-5.0000 -4.8990 -4.7980 -4.6970 -4.5960 -4.4949 -4.3939 -4.2929
Notice the structure of this variable. Throughout this course, it will be very important to keep track of which
variables are scalars and which are vectors. As you learned in Calc 3, you can multiply scalars and vectors
together as so:
c*x
ans = 1×100
-15.0000 -14.6970 -14.3939 -14.0909 -13.7879 -13.4848 -13.1818 -12.8788
Plotting
Now we have defined x, which is a discrete (i.e. not continuous) representation of the interval [-5,5]. What
happens now if we try to define ?
y = x.^2
y = 1×100
25.0000 24.0001 23.0206 22.0615 21.1228 20.2046 19.3067 18.4292
Notice that if we try the syntax used for scalars (y=x^2), we get an error message. That is because there
is no mathematical definition for "squaring" a vector. However, if we use the syntax (y=x.^2), we get no
error message now. That is because what we really need to do is an element-wise operation. That is,
1
each individual element of the vector is getting squared. Note that element-wise operations also apply to
multiplication and division. For example, if we want to define , we do the following:
z = x.*y
z = 1×100
-125.0000 -117.5763 -110.4524 -103.6223 -97.0797 -90.8185 -84.8325 -79.1154
x./y
ans = 1×100
-0.2000 -0.2041 -0.2084 -0.2129 -0.2176 -0.2225 -0.2276 -0.2329
Now, suppose we want to plot y and z versus x, label our axes, and add a title. We do the following:
Note the use of the "hold on" command. This is necessary for plotting multiple curves on the same plot.
Matrices
2
For specifics on matrix-vector multiplication and solving systems of equations in MATLAB, please refer to the
document under module 1 on canvas.
As the first three letters suggest, MATLAB works heavily with matrices and vectors to enable efficient
calculations. There are some effecient commands for making specific kinds of matrices, and you will get
some practice with those in problem 3 of worksheet 1. Let's suppose we want to make a simple 3 x 3 matrix,
we do the following:
A = [1 2 3; 4 5 6; 7 8 9]
A = 3×3
1 2 3
4 5 6
7 8 9