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

- manipulate arrays with more than 2 dimensions,
- write and use functions,
- perform coordinate transformations (rotations and/or translations), and
- create multiple plots in one figure.

At the end of the lab you will turn in three 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 two files are function files "pickShape.m" and "rotTrans.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.

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.

Load the file shapes.mat to your computer so that you can see it in th. Go to the "Current Directory" window of MATLAB and navigate to that directory (if the window is docked, you might have to undock it, browse to the proper directory, then re-dock it). At the MATLAB prompt enter

>>load shapes

This will load a variable "shapes" this is a 3x5x4 matrix. In other words the matrix has 3 rows, 5 columns and 4 "layers." Display the variable:

>> shapes

shapes(:,:,1) =

0 1 1 0 0

0 1 0 0 0

1 0 0 0 0

shapes(:,:,2) =

0 0 2 3 0

0 1 1 0 0

0 1 0 0 0

shapes(:,:,3) =

0 0 1.0000 1.0000 0

0 1.5858 0.5858 0 0

0 0 1.0000 0 0

shapes(:,:,4) =

0 0.7071 0.4142 1.8284 2.8284

0 0.7071 1.0000 1.0000 0

0 1.0000 1.0000 0 0

Each "layer" of the matrix represents a shape. For instance consider the top layer:

The top row, [0 1 1 0 0], is a set of x values, the second row, [0 1 0 0 0], is a set of y values and the first three elements of the third row is a color, [1 0 0] (red).

If you want to examine the shape you can make a patch object:

>> myRedTriangle=patch([0 1 1 0 0],[0 1 0 0 0],[1 0
0]);

>> axis([-2 5 -2 5],'square'); grid on;

Note that even through the patch has 5 "x" and "y" values in (x,y) pairs, the first, fourth and fifth (x,y) pairs are all (0,0). Therefore there are only 3 distinct (x,y) pairs, and these describe the triangle shown.

→ **MATLAB Cell
1:** Go to the MATLAB command
window and choose . In this script adapt the code below so that the red triangle is displayed
by extracting the appropriate sections of the "shapes"
array.
Replace the question marks in the code as necessary and add comments to
explain.

xShape1=shapes(?,?,?) yShape1=shapes(?,?,?) color1=shapes(?,?,?) s1Patch=patch(xShape1,yShape1,color1); axis([-2 5 -2 5],'square'); grid on;

Recall that the beginning of a "cell" is a line of code that starts with "%% " (two percent marks and a space - the space is important). You might want to add code at the top of the cell like the following

disp(' '); disp('Cell 1');

This will print a line in the MATLAB command window identifying the cell. This will be useful later when you run the code when it has multiple cells.

Write a function called "pickShape" that takes two input arguments, the "shape" matrix, and a number, "n", from one to four that specifies the shape. It should have three output arguments, "xShape", "yShape", and "cShape" that represent the x values, y values and the color of the chosen shape. The first line of the function describes the function syntax:

function [xShape, yShape, cShape] = pickShape( shape, n )

A template function is given in the file "pickShape.m". Download it into your directory and complete it.

Now you should be able to get all of the information to define shape 1:

>>> [x1,y1,c1]=pickShape(shapes,1)

x1 = 0 1 1 0 0 y1 = 0 1 0 0 0 c1 = 1 0 0

>> shape1=patch(x1,y1,c1); axis([-2 5 -2 5],'square'); grid on;

Repeat for shapes 2, 3, and 4 (by replacing the "1" in the second argument call of the "pickShape" function. You may want to clear the axes ("cla") between plots.

Save your "pickShape" function to SwatFiles (or email it to yourself). You will be using it again next week.

Use MATLAB's "subplot" function to put all four
shapes on the screen at the same time, each in its own set of axes as shown
below. The
subplots should be labeled "Shape 1", "Shape 2", ...
To learn how "subplot" works, look at documentation
(>> doc subplot) or use your textbook. A
*for...loop* can be helpful here (look for any code that looks repetitive
and try to figure out how to use a for loop).

→ **MATLAB Cell
2: **
Write MATLAB code that shows all four shapes
simultaneously, each in its own plot, using MatLab's "subplot"
function, and your "pickShape" function.

Recall that the beginning of a "cell" is a line of code that starts with "%% " (two percent marks and a space - the space is important).

A brief review of coordinate transformations from class:

Starting with a point (x,y) you can rotate it about the origin by an angle
θ and translate it in the x and y directions by t_{x}, and t_{y}, resulting in a
new point (x',y') by doing a matrix multiplication by the transformation matrix,
**T**.

In this example θ is approximately 15°, this rotates the point around the origin by that amount. After the point is rotated around the origin by θ, it is translated to the left (i.e., t _{x} is negative) andupwards (t _{y} is
positive). |

You can similarly transform multiple points (x_{1},y_{1}), (x_{2},y_{2}),
… (x_{n},y_{n}) by forming them into a matrix before
multiplying.

Write a function called "rotTrans" that has five input variables:

- x_in: a row vector of x values.
- y_in: a row vector of y values.
- theta: an angle, in degrees, for rotation.
- tx: distance to translate in x.
- ty: distance to translate in y.

and two output variables:

- xp: rotated and translated values for x.
- yp: rotated and translated values for y.

The first line of the function should look like:

function [xp yp] = rotTrans( x_in, y_in, theta, tx, ty )

It should be called with the syntax

[xp yp] = rotTrans(x, y, theta, tx, ty)

Remember: before you do the transformation you need to create an array whose first row is the x vector, second row is the y vector and third row is all ones (check out MATLAB's "ones" function: >> doc ones).

To test your function try the following and make sure you get the correct results:

>> x=1; % x value of point >> y=1; % y value of point >> % rotate the point (1,1) by 90 degrees, result should be (-1,1) >> [xp,yp]=rotTrans(x,y,90,0,0)

xp = -1 yp = 1

>> % translate (1,1) by tx=-1, ty=2, result should be (0,3) >> [xp,yp]=rotTrans(1,1,0,-1,2)

xp = 0 yp = 3

>> % rotate (1,1) by 90 degrees then translate by tx=-1, ty=2. Result is (-2,3) >> [xp,yp]=rotTrans(x, y, 90, -1, 2)

xp = -2 yp = 3

Save your "rotTrans" function to SwatFiles (or email it to yourself). You will be using it again next week.

→ **MATLAB Cell
3: **Verify that your "rotTrans" function works for
individual points by including the code shown below (use the code below
but fill in the question
marks).

disp(' '); disp('Cell 3'); % If we take the point (x,y)=(2,-2) and rotate it 180 degrees, % we get the point (?,?). If we then translate it by % by tx=1, ty=-1.5 we should get the point (x',y')=(?,?). % This is verified below. [xp,yp] = rotTrans(2,-2,180,1,-1.5)

→ **MATLAB Cell
4: **Verify that your "rotTrans" function works for
multiple points by creating a cell with the code shown below, but with
added comments.

disp(' '); disp('Cell 4'); x = [3 2]; y = [1 -2]; [xp,yp] = rotTrans(x,y,180,1,-1.5)

For each of the four pieces of the T-puzzle figure out how much each shape has to be translated and rotated to form the solution.

**The Pieces**

**The solution:**

→ **MATLAB Cell
5: **
Write MATLAB code that displays necessary translations and rotations using the
code below (fill in question marks and add comments). You should
figure out the necessary rotations and translations by examining the
original shapes. MATLAB is doing no calculations here - this code is
just to ensure that you know the correct transformations to make to the
shapes to get them in the proper place.

thetas = [? ? ? ?]; txs = [? ? ? ?]; tys = [? ? ? ?]; for i=1:4, disp(['Shape ' num2str(i) ' rotated by theta = ' num2str(thetas(i))]) disp(['and translated by [tx ty] = ' num2str([txs(i) tys(i)]) '.']) disp(' ') end

Save this information. You will be using it next week.

→ **MATLAB Cell
6: **Write MATLAB code that does the following:

- Make a figure with two subplots.
- In one subplot, define and place four patches derived from the "shapes" array with no rotation or translation (note that they will overlap each other, obscuring some; that's OK).
- In the second subplot, define and place four patches derived from the "shapes" array but with the pieces rotated and translated such that the puzzle is solved. Do this by changing the "XData" and "YData" properties of the patches in the second subplot. Use the "thetas", "txs" and "tys" arrays that you created in the previous cell for your code for this cell.
- Use the "pickShape" and "rotTrans" functions
- Use
*for...loops*as appropriate rather than retyping lines of code that are similar to each other.

If this is done properly, this section of the code can be quite compact (I used a loop with four lines in it that did all of the necessary tasks, including transformation and plotting needed for the second subplot). Hint: make the call to "pickShape" in a loop.

- To execute a single cell select " " at the MATLAB menu at the top of the screen (or type "Ctrl-Enter").
- To execute a single cell and move on to the next cell select " " (or "Ctrl-Shift-Enter").
- To execute the entire script go to " " (or " " if the file is already saved). Hitting the "F5" key also works.

(via moodle)

For this lab you are to turn in 3 files. Turn in one MATLAB script with multiple cells; each cell is devoted to one of the assigned tasks (magenta arrows, →). Turn in two function files "pickShape.m" and "rotTrans.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 a function file, you can get at most 2 points (for correct answer).