E5 MatLab, Lab 1
11/9/2000

For the next three labs you will be learning to use a program called MatLab (for "MATrix LABoratory") .   MatLab is an extraordinarily useful tool for all kinds of engineering analysis and design.

Log on to a PC, go to the "Start" menu and start the MatLab program.  The MatLab command window will appear:

In this document, your input to the MatLab window is green, MatLab output is red.  You should try all the commands by typing the green text into the MatLab command window.  If you aren't comfortable with matrices, you might want to refer to the handout from class.

## Vectors

At the prompt, », enter a row vector.

```» a=[1 2 4 5]
a =
1 2 4 5```

Now enter a column vector.  The tick mark, ', tells MatLab to take the transpose of a matrix.  Remember, a transpose is obtained by switching rows and columns in a matrix - so the transpose of a row vector is a column vector.

```» b=[3 -1 -2 3]'
b =
3
-1
-2
3```

You can also define a vector without having it displayed immediately by putting a semicolon at the end of the line.  Enter:

```» c=[1 2 3 5];
»```

To print out the value of one of the variables, just type it at the command prompt.

```» c
c =
1 2 3 5```

Now we can multiply the vectors:

```» a*b
ans =
8

» c*b
ans =
10```
```» b*a
ans =

3     6    12    15
-1    -2    -4    -5
-2    -4    -8   -10
3     6    12    15
```

1) You should verify, by hand calculation, that at least one of these three answers is correct.

Element by Element multiplication.

It is often useful to multiply the individual elements in a vector.  To do this, you use the element-by-element multiplication operator, a period followed by an asterix, .*.  In the following example, each element in d is equal to the corresponding elements in a and c multiplied together.

```» d=a.*c
d =
1 4 12 25
```

## Matrices

A matrix can be entered a row at a time, with a semicolon between rows.

```» A=[1 -2; 1 2]
A =
1    -2
1     2```

The identity matrix can be formed with the function eye(n), where n is the size of the desired matrix.

```» I=eye(2)
I =
1     0
0     1```

Let's also define a column vector, v:

```» v=[1 2]'
v =
1
2```

We can now do mathematic manipulations of these matrices, including finding the inverse of the matrix A Recall that A*A-1=I (where A-1 is the inverse of A).

```» A*I
ans =
1    -2
1     2

» I*A
ans =
1    -2
1     2

» A*v
ans =
-3
5

» B=inv(A)
B =
0.5000    0.5000
-0.2500    0.2500

» A*B
ans =
1     0
0     1```

2) Verify, by hand, the calculation of A*B.

## Matrix Applications

Matrices can be used to solve multiple simultaneous equations.  For example, consider the problem of solving 3 simultaneous equations:

This can be written in a matrix form as

where

3) Verify the preceding statement (i.e., show that Ax=b represents the set of equations)..

You can solve these equations by various substitution methods, or we can use matrices.

To do this using MatLab, do the following:

```» A=[1 2 3; 1 -1 2; 3 1 -1];
» b=[0 -2 5]';
» x=inv(A)*b
x =
1.0000
1.0000
-1.0000```

which is the correct solution.

4) What are x1, x2, x3, and x4 for the following set of equations?  Use MatLab to get the solution.

Static Equilibrium

A picture hangs on the wall from two strings as shown.

The picture has a mass of two kilograms.  We can sum the forces in each direction, where T1 and T2 are the tensions in the strings.

5) Find T1 and T2, using MatLab

(note: you'll have to move the "mg" term to the right hand side of the second equation).   You can use MatLab to find the sine and cosine, but first you must convert the angle to radians:

```» cos(30*pi/180)
ans =
0.8660

» sin(30*pi/180)
ans =
0.5000```

or you could use the fact that

or, with MatLab (using the SQuare RooT function - sqrt()).

```» sqrt(3)/2
ans =
0.8660```

Least Squares (Extra, if you have time)

You have probably all fit a line to a set of noisy data.  This can be made more precise through a technique called called the least squares method.  The graph below represents a series of measured values of a variable y, taken at certain times t, and a crude attempt to fit a line through the points.

The data values are given as pairs, (t,y): (2.5, 1.2), (5.0,2.2) , (7.0, 4.0), (11.0,10.0), (12.0,13.8).  Enter the values as two vectors of length 5 into MatLab, called ti and yi.  This choice of names will be clearer soon.

```» ti=[2.5 5.0 7.0 11.0 12.0]
ti =
2.5000    5.0000    7.0000   11.0000   12.0000

» yi=[1.2 2.2 4.0 10.0 13.8]
yi =
1.2000    2.2000    4.0000   10.0000   13.8000```

Now, lets make a plot using MatLab.

`» plot(ti,yi)`

This doesn't look like the original, so lets have MatLab plot with red x's instead of a line (type » help plot for more plotting options).  Also, add titles and rescale the axes.

```» plot(ti,yi,'rx')
» xlabel('t')
» ylabel('y')
» title('E5 Plot, t vs y')
» axis([0 15 0 15])```

To find the least squares line that best fits the data, we first define the function for a line (with intercept a1 and slope a2).

We want to find the values of the coefficients a1 and a2 that minimizes the sum squared error (sse) between the line and the data:

The quantities ti and yi are the experimental values taken from the graph.  The quantity (y(ti)-yi) is just the error between the fitted line and the experimental value for the ith datum.  We square it so the positive errors and the negative errors both contribute to the sum squared error.  The summation goes to 5 because there were 5 data values. We can re-write the expression as:

Now the task at hand is to find the values of a1 and a2 that minimize sse.  You can think of the sse as a function of both a1 and a2.  You know that to minimize a function, you just take the derivative and set it to zero.  Because we have a function of two variables, a1 and a2, we need to use what are called partial derivatives.  A partial derivative for our purposes is the same as a standard derivative, you just assume the other variables are constant.  A partial derivative is denoted by the notation "", rather than the standard "d" for a standard derivative.  So we take the derivative of the sum squared error, sse, with respect to a1 and a2 and set them both to zero.

The first equation can be simplified as

Similarly for the second equation

Since the ti and yi are known, this simplifies to two equations in two unknowns, a1 and a2.   If we let

and

We can reframe the problem as a matrix problem, with the vector a unknown.

The only difficulty remains calculating the sums.  Luckily, MatLab has a sum() function that will do just that.

```» c11=5;
» c12=sum(ti);
» c21=c12;
» c22=sum(ti.*ti);
» b1=sum(yi);
» b2=sum(ti.*yi);
» C=[c11 c12; c21 c22]
C =
5.0000   37.5000
37.5000  345.2500

» b=[b1 b2]'
b =
31.2000
317.6000

» a=inv(C)*b
a =
-3.5569
1.3063```

So the best fit line is y(t)=-3.56+1.31t.

Plotting the results.

Let's plot the equation above, along with the original data.  To plot the equation, we'll need a range of "t" values.  We can do this in MatLab by specifying a starting value, an increment value, and a final value.  For example, to create a vector that goes from zero to fifteen by three,

```» t=0:3:15
t =
0     3     6     9    12    15```

Let's use a much finer increment, so we get a nice plot (don't forget the semicolon, or you'll get a lot of numbers on the screen):

`» t=0:0.1:15;`

Now lets calculate y, and plot both the original data (red x's) and the fitted line (blue dotted line).  Again, you can type » help plot for more plotting options.

```» y=a(1)+a(2)*t;
» plot(ti,yi,'rx',t,y,'b:')
» axis([0 15 0 15])```

Extending the Least Squares Method

The method described above can be extended to any polynomial.  For example, it could be used to find the three coefficients that define the parabola given by:

6) Extend the least squares method to a second order polynomial, and find the best fit values for a1, a2, and a3.  Show your work, and include a plot of the parabola plotted along with the original data.