Introduction to MatLab
MatLab is an environment, similar to MathCad, which allows mathematical calculations and graphics. When you first call up MatLab (click on the icon) you are greeted with the following message:
This version is for educational classroom use only.
To get started, type one of these commands: helpwin, helpdesk, or demo. For information on all of the MathWorks products, type tour.
You can then type commands at the prompt (>>).
To see how it can be used on the simplest level, define variable x to be 3, variable y to be 4, and variable z to be the sum of x and y. The result will look something like this:
>> x = 3
>> y = 4
>> z = x + y
Matlab prints out the value of each variable automatically when you type each line. You can prevent it from printing this value if you place a semicolon after the line:
>> z = x + y; Will not print the value of z.
Other symbols of interest besides ‘+’ are ‘-‘ (subtract), ‘*’ (multiply), and ‘/’ (divide).
Do the following computations in Matlab to determine the value of b after each of the following is executed. Assume x = 3, y = 4, z = 5, p = 12.
>> b = y – x
>> b = p/x
>> b = z*x + 12/y
>> b = (z*x +12)/y
>> b = sqrt(p+y)
Of course, ‘sqrt’ stands for square root. Other mathematical functions are available, including:
sinh hyperbolic sine
asin arc sine
asinh hyperbolic arcsine
cosh hyperbolic cosine
acos arc cosine
acosh hyp. arc cosine
tanh hyperbolic tangent
cot co tangent
log natural log
log10 log base 10
log2 log base 2
imag imaginary part
real real part
conj complex conjugate
angle phaser angle
mod remainder after division (modulo)
Notice that MatLab can work with complex numbers, as implied by the ‘real’, ‘imag’, ‘conj’, ‘abs’, and ‘angle’ commands. For example:
>> x = 3 + 4i
Creates the complex number x with real part 3 and imaginary part 4. If in addition, we define:
>> y = 5 + 6i
Then these numbers can be manipulated. For example:
>> z = x*y
makes z = -9 + 38i.
>> z = x/y
makes z = 0.6393 + 0.0328i
One more example. It is known that a right triangle with opposite length 1 and adjacent length 1 has a 45 degree (π/4 radian) angle. So try this:
>> a = 1 + 1i
>> b = angle(a)*180/pi
As expected, this gives a value of 45 degrees. Note that the result must be multiplied by 180/pi to convert it to degrees from radians.
Matlab is even more powerful than this in that it can manipulate entire matrices. Let’s start with a simple array.
>> A = [1 2 3 4 5 6]
>> B = [2 3 4 5 6 7]
This identifies two arrays (or vectors) A and B. We can select any element of the array with B(3), which would give us the third element of B, i.e. 4. We can “multiply” A and B with:
Which yields C=[2 6 12 20 30 42]. Why did I put “multiply” in quotes? Because this is neither a cross product nor a dot product. It is simply the element-by-element product of the two vectors. Notice that you will not be able to say:
This is because A and B are both row vectors, and there is no definition for the product of two row vectors. However, there is a definition for the product of a row vector and a column vector such as:
This is just the dot product. To change B into a column vector, add an apostrophe after it. Thus:
Will give the result 40 as above.
Now extrapolate this to matrices with multiple columns. For example, to make a 3 by 3 matrix, you can say:
>> C=[[1 2 4]’ [5 7 9]’ [3 5 3]’]
(Note the apostrophes). This will create the matrix:
Which can then be manipulated. For example, define C as above and take the determinant:
You could also define this same matrix with:
>> C = [[1 5 3]; [2 7 5]; [4 9 3]]
Notice that the semicolon separates rows of the matrix.
How do I:
1. Set up a vector of 100 evenly spaced numbers? For example, a vector starting at zero and going to 10 in steps of 0.2 can be set up like this:
Most of the time you will want to put the semicolon on the end of this because it can get to be annoying when all 100 values are printed out.
2. Use this to calculate a function at all of the values of this vector? Try squaring the vector:
>> zsq = z.*z
Or taking the exponential
>> zx = exp(z)
Or something like this:
>> zdv = exp(z)./z
Notice the need for the ‘.’ in this expression. This expression exponentiates each component of the vector and then divides by that same component. For example, if z=[1 2 3], zdv becomes [exp(1)/1 exp(2)/2 exp(3)/3]
Typing in formulas gets old fast, so there should be a way of putting a formula into a file for later use. This can be done with the m-files. In an m-file you can type your commands in just as when you’re on the command line of Matlab, and then when you type the name of the m file, these commands are executed.
For example, from the Matlab menu, call File | New | m-file. Then type the following command:
z = x+y;
Then call File | Save As
Under the prompt type the file name “myadd.m”. Now go back to the main window of MatLab and type:
To find the value of z, simply type
MatLab should then respond with 24.
Of course, if you did not put the semicolon after z=x+y in the m-file, MatLab printed the value of z for you as soon as you typed “myadd.”
To close the m-file, enter m-file window and choose File | Exit Editor/Debugger.
Functions have a similarity to m-files, but they are different in that the variables are passed to them, as opposed to the file using whatever variables are set up on the command line. If, for example, “myadd” were a function, it would have no idea what the values of x and y were unless you told it.
For example, from the MatLab main menu, choose File | Open | m-file
Then type the following
Save this with File | Save (give the file the name “doadd.m”).
Now, back in the main MatLab window type:
You should get the same answer as you did before. The difference is that you have to tell “doadd” what you want to add, and it now returns that value to a variable of your choice (in this case ‘z’). Notice that the variable names in the file doadd (p and q) do not need to match those that you specify in the main MatLab window. The function knows what you want added from the argument list (i.e., (x,y)).
Now apply this to a more complicated example. Let’s say you wish to be able to calculate the value of a polynomial of arbitrary size. You could define a function “poly” which takes as its argument the coefficients of your polynomial and the value at which you want it evaluated. For example, if your polynomial looked like:
y = 12x3 + 3x2 + 5x + 8
The function might look like this:
p = a1*x*x*x + a2*x*x + a3*x + a4;
You can then call this function with:
>> y = dopoly(x,12,3,5,8)
to evaluate the polynomial.
But what if you want a more general function that will calculate the value of any polynomial? Consider the following:
sum = 0;
sum = sum + A(i)*xpow;
xpow = xpow*x;
p = sum;
If you call this with
>> A = [1 2 4 8 3];
>> x = 37;
>> y = dopoly(x,A);
you will get the value of
y = 3x4 + 8x3 + 4x2 + 2x + 1
In fact, this will work regardless of the order of the polynomial. You need only set the length of A correctly.
Now let’s say you want to find the roots of the polynomial. There is a numerical method for doing this called the Newton Raphson Iteration. Consider the figure below, which shows a polynomial curve with three roots (three points of intersection with the x axis). Let’s say that we guess a value of the root (Initial Guess). It’s probably not right, but we can still evaluate the value of the polynomial. We can then calculate the slope of the polynomial at that point (we need another function for this, but it’s easy to take the derivative of a polynomial) and draw a tangent line and follow it until it hits the x axis. This is also not correct, but it’s closer than our initial guess. If we repeat the process several times, and if our function behaves itself, we will eventually converge on the correct answer. This all hinges on our being able to determine the intersection point of the tangent line and the x-axis. This is not so hard. The tangent line has the equation:
(y-y0) = m(x-x0)
You will recognize this as the point-slope formula for a straight line. If we knew only one point on the line (x0,y0) and we knew the slope m, we would have an equation for the line. But we have both of these. If we evaluate the function at our guess (call the guess x0), then we would get y0 (call this f(x0)), so we would have a point on the line (x0,y0). The slope of the line is just the first derivative of f(x) evaluated at x0. We are interested in where the line crosses the line y=0, so if we set y=0 in the point-slope formula, we get:
-y0 = m(x-x0)
x = -y0/m + x0
In terms of the function we are interested, this can be written as:
x = -f(x0)/f’(x0) + x0
Now it is time to see if you understand all of this:
1. Write a MatLab function to calculate an arbitrary length polynomial, where the input is the value of x and an array of the coefficients. Test it with the polynomial
y = 3x4 - 8x3 + 4x2 - 2x + 1
at the points x = 1, 2, and 3 to make sure it works (use your calculator to make sure the function works).
2. Write a matlab function to evaluate the first derivative of the given polynomial. The input is again the value of x and the coefficients of the polynomial (not the coefficients of the derivative!). Again, check to make sure it provides the correct answers.
3. Find two roots of the polynomial given above using a Newton Raphson function. The input to the Newton-Raphson function will be just the coefficients of the polynomial.
Steven A. Jones