Lab 6:

Introduction to MATLAB


Objectives

  1. Learn how to manipulate matrices.
  2. Learn how to graph and plot data.
  3. Learn how to write scripts.



What Is MATLAB?

The name MATLAB stands for ‘matrix laboratory’. MATLAB was originally written to provide easy access to matrix software developed by the LINPACK and EISPACK projects. These projects represented the state of the art in software for matrix computation. MATLAB is an interactive programming system for scientific and engineering numeric calculation. It is especially good with matrices, but works well with scalars too. MATLAB also works as an interpreted programming language. Since anyone can write new functions at any time, it is highly extendible. Also, large libraries of function already exist and are available on the web. One great resource for already written and tested functions is:


http://www.mathworks.com



Using MATLAB


MATLAB is available for most platforms. Specifically there are versions for Mac, DOS, Windows, and UNIX. All of them behave in the same way. Files and scripts written for one version of MATLAB should work on all of them.


Basic use

Once you start MATLAB, you can use it similar to the scheme interpreter. For example, first try this:


3


MATLAB Returned:


ans =


3


The first thing you probably notice is that it has assigned the result to a variable named ‘ans’. MATLAB evaluates the expression and then assigns the result to something, so if you don't specify where to assign it, MATLAB will put it in "ans". Simple math in MATLAB is different from scheme because it evaluates simple math operators the way most of were taught math. Try this:


7 * 3


MATLAB Returns:


ans =


21



MATLAB is case sensitive. Therefore, the variable ans’ is different from the variable Ans’, and both are different from the variable ANS. As long as you are consistent in naming your variables, there will be no problem. So, pick one way to capitalize variable names and stick to it.


How do you find out the value of a given variable? There are actually many different ways to do that. The most appropriate method depends primarily on how you are trying to display the value. If you simply want it to evaluate the variable and display its value, you would type the variable's name. For example, if you wanted to know the value of the variable‘"ans"’, you would type:


ans



Printing to the Screen


If you want it to display the variable's value in a sentence, you would use fprint (formatted print):


fprintf('The value is: %4.2f \n', a)


Let us look at the previous line carefully. First, we have a call to the function fprintf. We pass a string in single quotes. That string contains what we want printed on the screen, and where we want it to fill in values we use a %X. There are three choices for the letter after the %. They are as follows:


%f

Fixed point (decimal notation)

%e

Exponential notation

%g

Shorter of %e or %f


If you use the %f option, you can specify how many decimal places you want it to display. This is done by putting a decimal number between the % and the f. For example if you want to print out the number 72.14837897797 with two decimal precision you would use:


%5.2f


This means in five positions (The decimal point is one of those positions) print with 2 decimal precision. So the output would look like:


72.15


Another interesting thing to notice about the above command is the ‘\n’. In many programming languages, this is a carriage return. This means ‘\n’ forces everything which comes after it to be on the next line. Try the above statement again, but this time omit the ‘\n’ and see what effect it has. Although it printed what you told it to print, the next command prompt was printed directly at the end of the sentence.


Another way to print to the screen is with the "disp" command (short for display). To print the value of a variable using disp, you would type:


disp('The answer is'); disp(ans)


This would return:


The answer is

12


Note how we put both commands on the one line separated by a semicolon. This tells MATLAB to execute both of them together without prompting you in between.



Use of the semicolon:


In the last section, we used the semicolon to separate two different commands on the same line. That is one of its uses, but unlike many programming languages, a semicolon is NOT required at the end of every line. In fact, putting one on each line could be an error. To figure out what a semicolon does, try this:


ans

ans;


Note that the first command returned the value stored in ans. However, the second one did not. So, it looks like the semicolon suppresses output. In other words, MATLAB executed the command, but MATLAB did not display the results to the screen.


Every statement in MATLAB returns a value. If you type:


MyAge=21


This assigns the value 21 to the variable MyAge. You will notice that it immediately returned


MyAge =

21


However, you already knew that. If you write a script that makes thirty variable assignments and each one returns a line like that, your screen would have so much text that you wouldn't be able to read it all. Worse still, you might miss an important line of output. Therefore, you would use a semicolon at the end of most assignment lines in a script to prevent all that output.


Matrices


One of MATLAB's specialties is matrices. Much of the work done with matrices can be fairly tedious. However, you can solve a many mathematical problems using a matrix. First, we should look at how to enter a matrix:


a=[10,34,59,89;23,83,58,34;43,43,32,40;3,83,77,17]


you get:

a =


10 34 59 89

23 83 58 34

43 43 32 40

3 83 77 17


Notice how you need to separate each entry by a comma. You separate each row by a semi-colon. For another example, you should define B as follows:


b=[1,3,5,7;2,4,6,8;10,20,30,40;8,37,14,2]


you get:

b =


1 3 5 7

2 4 6 8

10 20 30 40

8 37 14 2


Now we can do some math with the matrices. First, let's multiply them together. Type


a*b


you get:

ans =


1380 4639 3270 2880

1041 2819 2829 3213

769 2421 1993 2005

1075 2510 3061 3799


Remember that matrix multiplication is not simply each term multiplied by its corresponding term in the other matrix. The rules are as follows:


Given the two matrices, Matrix 1 and Matrix 2, whose values are:


Matrix1 = [ a1 b1 ]

Matrix2 = [ a2 b2 ] [ c1 d1 ] [ c2 d2 ]



[ (a1*a2 + b1*c2) (a1*b2 + b1*d2) ]

[ (c1*a2 + d1*c2) (c1*b2 + d1*d2) ]



The dot tells MATLAB to do straight, scalar multiplication on each entry.


Next, let's add them:


a+b


you get:

ans =


11 37 64 96

25 87 64 42

53 63 62 80

11 120 91 19


That was straightforward. MATLAB just adds each entry to its corresponding entry in the other matrix.


Finally, let's calculate the inverse of the matrix. MATLAB has a predefined function to do that:


inv(a)


returns:

ans =


-0.0092 -0.0302 0.0406 0.0129

-0.0038 0.0543 -0.0263 -0.0271

0.0016 -0.0627 0.0299 0.0466

0.0126 0.0242 -0.0144 -0.0220



Now do the following. Make sure you cut and paste your results into a separate text file to turn in. Given matrix A and B:



A =


1 2 3

2 5 3

1 0 8



B =


18 15 46

2 35 23

1 3 99



Graphing and Plotting:


MATLAB has the ability to plot data. Let us look at one example.


In this experiment, the distance a remote-controlled car traveled on a hill was recorded. The experiment was repeated 10 times. The following data was recorded.



Trial

Distance (ft)

1

58.5

2

63.8

3

64.2

4

67.3

5

71.5

6

88.3

7

90.1

8

90.6

9

89.5

10

90.4


First, we must put each set of data into an array (or matrix with one row). We can do that as follows:


Trial = [1,2,3,4,5,6,7,8,9,10];

Distance = [58.5,63.8,64.2,67.3,71.5,88.3,90.1,90.6,89.5,90.4];


Now to plot it, simply type:


plot(Trial, Distance)


If you want a nicely labeled graph, try:


plot(Trial, Distance), title('Laboratory Experiment 1'),…

xlabel('Trial'), ylabel('Distance, ft'),grid


This is the first time that we have come across a '...' This is called an ellipsis. In MATLAB, this just means that the statement is carried over on the next line (i.e. you use it if a line is too long to fit on a single line).


There are many ways to alter the look of your plot. You can always look up functions by typing:


help <function name>.



MATLAB Basic Scripting

Setting the path


Before creating any new functions in MATLAB, you must first set the path so that MATLAB knows where to find your new files. The path is the listing of directories that MATLAB looks in to find program files. You can set the path with the following command:


path(path, 'c:\temp');


This tells MATLAB to set the path equal to the old path plus the new directory, in single quotes. Of course, you can use something other than "c:\temp" if you want, but make sure that whatever directory you choose is where you put your script files.


Writing Scripts (New Functions)


You can add new functionality to MATLAB by creating new functions. To do this, you first must write the function and then place it in a file called


<function name>.m


in the working directory you specified when setting the path. Functions should be written in ASCII by such applications as pico or Notepad (or MATLAB's built-in scriptwriter).


Let us go through the process of creating a simple function using a function that we have used in scheme--quadratic. Call it MyQuad. As you know, the function calculates the roots of a polynomial. You remember the formula:




Here is how the function would look:


function [Root1, Root2] = MyQuad(A,B,C)

% MyQuad Calculates the 2 roots of a quadratic,

% given A, B and C.

%

Bottom = (2*A);

Quotient = sqrt((B*B) - (4*A*C));

Root1 = (-1*B + Quotient) / Bottom

Root2 = (-1*B - Quotient) / Bottom


Create a text file containing the above data and save it as MyQuad.m (you should know how to do these things by now). Before figuring out what the script does line by line, try it out and make sure it works. To do this, go back to the evaluation window and type:


MyQuad(1,8,15);

(If the path is set correctly, this is all you have to type to run the function. You do not specifically "load" the file like Dr. Scheme.)


If you did everything correctly, Root1 will be -3 and Root2 will be -5.


Now, let us examine the code line by line:



[Root1,Root2]=MyQuad(1,8,15)



In you don't already know must of us around here (the staff of cs1311x), you can get all of our health information from NBC's Dateline. One night, Dateline ran a story about how to use a special formula to determine if a person is overweight. The formula is:


INDEX = (704 * your weight in pounds) / (your height in inches ^ 2)


FYI: According to NBC, if the value of INDEX is 25 or less, you're in great shape. If the value of INDEX is 30 or more, you're at significant risk for heart disease and other weight-related problems.


An example for a 150 pound, 6 ft. tall person would be:


Index(150 72)


Now, write the Index function to figure out a person's Dateline Index.



Besides being health-conscious people, we also like to watch and play a lot of sports. However, it is often hard to calculate some of the statistics, especially for baseball. Most of us have a hard time trying to figure out a batter's slugging percentage. If you are not familiar with baseball, that's okay. We tell you how to calculate it. Create another function called Slugging using the following information:



So if we want to find a player's slugging percentage with 585 times at bat, 158 hits, 15 doubles, 4 triples, and 40 homeruns, we would type:


Slugging(585 158 15 4 40)


You may be asking yourself, "What about singles?" Remember that total hits includes singles, doubles, triples, and home runs.



Other Useful Functions


You will find that MATLAB has almost every function that you could ever want already built in. All you have to do is find it. Here is a list of some of the most common ones. To find out more details on what a function does, you can type:


help <function name>


You can also type "help" on a line by itself, and MATLAB will give you list of places you can look for new commands to try.




Your Assignment


You should have already done these if you read the lab. Put all of these into one file and submit it the way you always do.




  1. Write the matrix operations.

  2. Write the Index function.

  3. Write the Slugging function.