# Even More MATLAB; Let's Get Animated

Upon completion of the lab you should be able to use MATLAB to

• write nested for loops to animate graphical objects,
• execute conditional code with "if" statements
• fit data to a line given "x" and "y" data , and
• use the formula for a line to calculate an "x" value given a "y" value.

At the end of the lab you will turn in two  files.  One is a MATLAB script (.m file) with code in several cells; each cell will be the solution to a different part of the lab (marked by magenta arrows: ).  The other is a function file "getPCs.m" described in the lab directions below.  See the end of this web page for directions on what, precisely, needs to be turned in.

Feel free to consult with each other but don't ask for (or provide) completed solutions.

## Getting extra help:

If you find that you would like extra help, the following resources are available (in no particular order):

• Work with your classmates - don't simply copy from each other, but do feel free to work together.  Your code and answers should not be identical to anybody else's.
• See me during lab, or make an appointment to see me outside of lab (x8076, erik_cheever@swarthmore.edu, Hicks 305), or just drop by my office.  My schedule is here - feel free to drop by anytime I don't have something else scheduled.
• Talk to Ann Ruether (x8081, aruethe1@swarthmore.edu, Hicks 308), the Academic Resources Coordinator.
• Get help from Wizards in the lab.
• Go to E5 Wizards sessions on Mondays or Tuesdays 7:30-9:30.

## Getting Started

You may want to be familiar with chapters 3 and 4 of your text (and chapter 5 if you are feeling ambitious, thought this isn't strictly necessary).

## Animation

### Warm up exercise: A for...loop

Load the file shapes.mat into a directory in your user folder.   Also load your "rotTrans.m" and "pickShape.m" function files that you wrote for the last lab in the same folder (or you can use mine, rotTrans.m, pickShape.m).  Save the file,  cell7_1.m (shown below), in the same directory as the other files.

Run the "cell7_1" script.  It should solve the puzzle (your task from last week), but uses arrays to store the patches as well as the necessary rotations and translations.  To make sure you understand it, add detailed comments to explain exactly what the program is doing.  You don't need to worry about the "emode" variable (yet).

MATLAB Cell 1: Start a new script for this lab.  Paste the code for cell7_1.m into "Cell 1" of the new script.  Add comments to the code to indicate that you fully understand how it works..   Make sure the final (solved) image is also shown  shown.

### Again with the "for...loop" (this time for animation)

Load the file cell7_2.m into your directory and add code that animates the pieces (one at a time) as they move from their original position (with theta=0, tx=0, and ty=0) to the final position in several (10-20)  steps (or more, if you are ambitious) with a brief pause between steps.  The final animation should look something like the one below.  You will need to generate a set of linearly spaced angles and translations for the animation, and then iterate through them (using the rotTrans function).

When you are done writing your code, select all of the code in the editor and then go to (this will make your code easier to read by properly indenting all loops).  It is a good idea to do this periodically when writing large chunks of code.  It makes it much more readable.

MATLAB Cell 2:  Include the code that performs the animation.  Make sure it is properly commented and indented.

Try different values for the "emode" variable (possible values are 'xor', 'none', 'background', and 'normal').  This is the erase mode for the patch function.  Before a patch can move to a new location it must be erased from it's old location.  This variable changes how the patches are erased as you move them around.  If you are curious, I can discuss these with you.

### Writing an "if..." clause

If you watch the animationabove, you will notice that pieces that rotate to a positive theta rotate in a counterclockwise direction, those with a negative theta rotate clockwise.

Add an "if..." statement to your code such that all angles that are less than zero are converted to the equivalent positive angles (you can do this by adding 360 degrees), so that all parts rotate counterclockwise.  Do not just change the definition of the "theta" variable at the top of the file.

MATLAB Cell 3:  Include the code that rotates all objects counterclockwise.

### Yet again with the loops.

Write code in a new cell (cell 4) that animates the pieces so they move as in the animation below (first rotating, then translating in the x direction, then translating in y).  The direction of rotation isn't important.

MATLAB Cell 4:  Include the code that performs the specified animation.

### Ah, penny, brown penny, brown penny, I am looped in the loops of her hair

Write code in a new cell (cell 5) that animates the pieces so they move as in the animation below.    The direction of rotation isn't important.  Think about this - it can be done with a relatively small modification of some of your previous code.

MATLAB Cell 5:  Include the code that performs the specified animation.

## Fitting data to a line and finding a point on that line.

Consider the code below:

pcA=[125 10 63 188 245];        %pulse count in 4 microsecond intervals
thetaA=[-4 -41 -18 22 46];     %angle (degrees)

plot(pcA,thetaA,'bs');
xlabel('Pulse count (4\muSecond intervals)');
ylabel('Angle \theta_a (degrees - \circ)');
title('Pulse count vs. angle of motor A');
axis([0 250 -60 60]); grid on; 

At this point it isn't important what the "pcA" and "thetaA" data represent; you will use this in the next lab.  The variable "pcA" indicates the width of a pulse (in 4 μS increments), and "thetaA" is an angle (in degrees).

Paste the code into a new cell (cell 6).  Run it and you should get a plot like the one shown below:

We would like to find a line that accurately fits the data.  MATLAB does this with the polyfit" command.

Add the following code to the cell to find the slope and intercept of the line that "best" fits the data.

p=polyfit(pcA,thetaA,1); % Do a first order (linear) fit of the data
mA=p(1);                 % slope of fit
bA=p(2);                 % intercept of fit 

Now add code that plots the best fit line on the same graph and adds a legend so it looks something like the plot below:

MATLAB Cell 6:  Cell 6 should include all of the code that generates the graph shown above.

### Using the best fit data to find a pulse width given an angle

In the next lab you will be using two motors whose angles you want to control.  To do this you will control the width of pulses sent to the motor (at this point, don't worry how this is done, or even exactly what it means).  Your final task is to write a function that has two inputs (the angles "thetaA" and "thetaB") and uses the best fit lines to find two outputs (the associated pulse counts "pcA" and "pcB").  The quantities "mA" and "bA" are the slope and intercept of the plot for angle "thetaA" vs "pcA" (as seen above) and "mB" and "bB" are the slope and intercept of a similar plot for "thetaB" vs "pcB" (the plot is not shown).

Download the function below, getPCs.m, into your directory.  Complete the code so that you can specify angles thetaA and thetaB and the function returns the appropriate pulse widths.

You can test the function by entering the following code into a new cell (cell 7):

[pCountA pCountB] = getPCs(-40, 0)

The values for "thetaA" and "thetaBare -40° and 0°, respectively.  The returned pulse counts, "pCountA" and "pCountB" should be close to 10 and 120, respectively.

MATLAB Cell 7:  Include code that calls your "getPCs" function and verify that the result is close to what is expected.  The values returned should be integers (the "round" function rounds a real number to the nearest integer).

## To turn in

(via moodle)

For this lab you are to turn in 2 files.  Turn in one MATLAB script with multiple cells; each cell is devoted to one of the assigned tasks (magenta arrows, ).  Turn in one function file, "getPCs.m."  There is no need to turn in a "published" Word document.  Grading of each cell and function is on a ten point scale:

• 4 pts for clear and thorough commenting of your code.
• 4 pts for clearly written and concise MATLAB code
• 2 pts for the correct result (if it is clearly written and coded, the answer should be correct).
• If you don't turn in the function file, you can get at most 2 points (for correct answer).