E5 Lab 5
Introduction to MatLab
2007

For this lab 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.   You can download it from the Data_Software server onto your computer.

Go to a computer and start the MatLab program.  The MatLab command window will appear.  The window has several panes.  We will be entering commands into the "Command Window".  Defined variables appear in the Workspace window (upper left side) and previous commands appear in the "Command History" window (lower left).

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 array handout.


To Turn in:

By Thursday 10/11/07 post the answers to the questions in pink on your website.   You may choose to work alone, but if you choose to work in a group, make sure that everybody in the group gets approximately the same amount of time at the keyboard. If you do collaborate, you must acknowledge the names of collaborators on the document you post (you can scan in a hand-written document and post the .pdf file with a link in your website).


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

Plotting functions

Matlab can be useful as a tool for plotting functions.  For example, lets plot a sinusoidal function.

First, generate a time vector that will be used for plotting.

>> t=0:0.1:10;

This generates a vector t that goes from 0 to 10 with an incremental value of 0.1.  In other words t=[0 0.1 0.2 ... 9.9 10.0].

Now lets create another vector, x1, that is the sine of t, with a frequency of 2 radians per second.  Then we'll plot it.

>> x1=sin(2*t);
>> plot(t,x1);
>> xlabel('Time');
>> ylabel('x1');
>> title('x1 vs time');
>> gtext('This shows x1 vs time');

The last statement produces a cursor that allows you to place the text anywhere you want it.  The resulting figure should look like the one shown below.

Now lets create and plot some more functions.  At this point it is useful to point out that the up-arrow key scrolls through past commands.  If you type a character and then the up-arrow key, it scrolls through past commands that start with that letter.

>> x1=cos(t);
>> x2=cos(3*t)/9;
>> x3=cos(5*t)/25;
>> x4=cos(7*t)/49;
>> x5=cos(9*t)/81;
>> plot(t,x1,t,x2,t,x3,t,x4,t,x5);
>> legend('x1','x2','x3','x4','x5');

While there is no obvious relationship between these functions, one can be found.  Plot the sum of the 5 vectors; it should represent a triangle wave.   This is a demonstration that any function can be made up of sine waves. 

6) Turn in a clearly labeled graph of the resulting approximation to a triangle wave.

Subarrays

In Matlab, it is also possible to work with just parts of arrays.  For example, if we want to plot just the first 50 points of the array x1, we can use the colon operator, ":", to take indices 1 through 50 (1:50).

>> t=0:0.1:10;
>> x1=sin(2*t);
>> plot(t(1:50),x1(1:50));

7) Use the colon operator to plot the function for one period starting near the zero crossing at 1.57 seconds.  Turn in the MatLab command you used, as well as the graph.


Numerical differentiation in Matlab

Matlab can be used to approximate the process of differentiation.  Let's start with the same vectors as before.

>> t=0:0.1:10;
>> x1=cos(2*t);
>> y=diff(x1)./diff(t);

8a) Find out what the "diff()" function does (">> help  diff" or ">> doc diff"), and explain why the variable y will be approximately the derivative of x1.

Try plotting the vector y vs the vector t (">> plot(t,y)" ).  You'll find it doesn't work because the vector y is a different length than the vector t.  To see their respective sizes you can type ">> size(y)" and ">> size(t)" or you could use  ">> length(y)" and ">> length(t)", since they are one dimensional vectors. To see all variables that are currently in use, type ">> whos".  You can also see all variables defined in the workspace pane on the left side of the MatLab window.  To fix the size incompatibility problem, make the y vector one element longer, then we can plot both functions.

>> y(length(y)+1)=y(length(y));
>> plot(t,x1,t,y);
>> legend('cos(2*t)','derivative');

9) Explain how the first of the three lines fixes the plotting problem.

10) Is the function y what you expect?  Why or why not?

Why we don't normally use numerical differentiation.

Let's add a little bit of random "noise" to the cosine and plot again.  This noise can be from experimental measurements, or just due to the fact that we can't represent numbers exactly in a computer.  Notice that the signal doesn't look too bad, but the derivative is a mess.

>> x=cos(2*t)+0.1*randn(size(t));
>> y=diff(x)./diff(t);
>> y(length(y)+1)=y(length(y));
>> plot(t,x,t,y);
>> legend('cos(2*t)+noise','derivative');
>> title('Differentiation with a little noise')

11) Explain what the first line does.


Numerical integration in Matlab

Matlab can also be used to approximate the process of integration, with more success.   The figure below represents the process of approximating an integral.

 

Let's start with the same vectors as before.

>> t=0:0.1:10;
>> x1=cos(2*t);
>> y=cumsum(x1.*diff(t));

This generates an error because x1 is incompatible with the vector returned by diff(), as you can tell by checking their sizes.  So we can do the following:

>> y=cumsum(x1(1:(length(x1)-1)).*diff(t));
>> y(length(y)+1)=y(length(y));
>> plot(t,x1,t,y)
>> legend('cos(2*t)','integral')

12) Explain why the variable y will be approximately the integral of x1.  You might want to refer to the image above when answering.

13) Is the function y what you expect?  Why or why not?

Integrating in the presence of noise.

Let's add a little bit of random "noise" to the cosine and plot again.  Notice that we don't have the same problem as we did with differentiation.

>> x=cos(2*t)+0.1*randn(size(t));
>> y=cumsum(x(1:(length(x)-1))).*diff(t);
>> y(length(y)+1)=y(length(y));
>> plot(t,x1,t,y)
>> legend('cos(2*t)+noise','integral');
>> title('Integration with a little noise')

14) Explain why numerical differentiation is inferior to integration in the presence of noise.  To figure this out, consider exactly what it is that both processes do.


Just for Fun - Symbolic Manipulations

We will be using MatLab predominantly as a fancy calculator, but it can also be used to do algebra and calculus symbolically.  Try the following.

We can solve the matrix problem from above:

>> [x1, x2, x3]=solve('x1+2*x2+3*x3=0','x1-x2+2*x3=-2','3*x1+x2-x3=5')

We can also solve the picture hanging problem for any angles and masses.   First define some symbolic variables to represent the quantities in the problem.

>> syms theta1 theta2 m g

Now define the matrices and solve:

>> syms theta1 theta2 m g
>> A=[cos(theta1) -cos(theta2); sin(theta1) sin(theta2)]
>> b=[0; m*g]
>> T=inv(A)*b

The result is a bit unwieldy.  We can try several ways to simplify it.

>> simple(T)

Or we can just pick the most compact.

>> T=simple(T)

If we want to solve for particular values, we can set the variables and then evaluate the expression.

>> theta1=30*pi/180;
>> theta2=60*pi/180;
>> m=2;
>> g=9.8;
>> eval(T)

We can also do some simple calculus (differentiation and integration).

>> syms t
>> y=cos(2*t)
>> diff(y,t)
>> int(y,t)
 

We won't be using the symbolic capabilities of MatLab in this course, but they can be quite convenient.  To find out more:

>> doc symbolic