1
Lab 6: MATLAB Exam Review
Due Saturday Oct 10, 2020 at 11:59PM EDT on Gradescope. This lab is worth 40 points and is graded for completion. However, earning a grade depends on attendance and participating during the lab - this will be verified by the staff member joining your meeting.
Lab meetings last 90-120 minutes. You work as a group for the first 60 minutes and a member of the course staff will join your call for the next 30 minutes to check-in and answer questions. The remaining 30 minutes are there if you need them.
Introductions
Welcome to Lab! Before jumping in to the worksheet, encourage your team to warm up by each taking a turn giving your response to the following question to the group:
“If you could travel to any place and time, where would you go?"�
REMINDER: If you get stuck on one of the exercises, feel free to move on and come back to it after checking in with your Coach. We are happy to answer any questions!
HEADS UP: If a question says Person D or E is the discussion leader, but you don't have that many members, the Leader should lead the discussion for that question.
THIS IS NOW a real slides document instead of background images. So you can copy/paste and click on links and everything! But please don't move or resize the tables/boxes or add pages. We need them to stay in place for grading!!!
Our team name is... | |
| Name | Time joined call | Roles (groups of 3) | Roles (groups of 4) | Roles (groups of 5) |
Person A | | | Scribe Leader | Scribe | Scribe |
Person B | | | Googler Questioner | Googler Questioner | Googler |
Person C | | | Coder | Coder | Coder |
Person D | | | | Leader | Questioner |
Person E | | | | | Leader |
Staff | | | Coach | ||
Before You Start! A few things…
Administrative stuff
Lab Overview
For this lab we will be reviewing some of the more commonly used tools and topics that we’ve learned in MATLAB so far. Think of this lab as a supplement to your review process for the MATLAB exam on Monday October 12th. Although we will cover a lot in this lab, it is NOT an exhaustive list of everything we have covered in the course so far, and therefore this lab is NOT an exhaustive review of material that may be on the exam.
�To refresh everyone’s memories on some of the many topics we’ve learned so far, there are many subjects in this lab and there is a lot of coding to be done. Please share the coding responsibility among yourselves and DO NOT leave it just to the coder. Everyone should get some practice with the material in this lab to better prepare yourselves for the exam. Use your time wisely and this should help you identify any MATLAB topics with which you might not yet be completely comfortable -- those are the things to review for the exam!
2
Important! Do not delete slides, rearrange slides, or in any other way change the format of these lab slides. If you do, then we’ll have trouble grading and you might get a zero, and that would make us all sad because then we have to do regrades and we hate doing regrades. |
Review: The Basics
Vectors & Matrices (~5 min)
You have the following vectors and matrices:
A = [7, 4, 8, 5];
B = [3, 6, 9, 10];
C = 1;
D = [ 2, 4; 3, 6];
Working simultaneously, fill out this table:
As a group, review the results. The Questioner should write down any questions that you have for the Staff Coach.
3
| Person Evaluating Expression | MATLAB expression | Value of X |
1 | PERSON C | X = A(2) | |
2 | PERSON B | X = B(end) | |
3 | PERSON A | X = D + C .* 5 | |
4 | PERSON E | X = A + C | |
5 | PERSON D | X = D(2,1) | |
6 | PERSON C | X = B .* A | |
Logical Indexing (~5 min)
You have the following vectors and matrices:
A = [7, 4, 8, 5];
B = [3, 6, 9, 10];
C = 1;
D = [ 2, 4; 3, 6];
Working simultaneously, fill out this table:
As a group, review the results. The Questioner should write down any questions that you have for the Staff Coach.
4
| Person Evaluating Expression | MATLAB expression | Result |
1 | PERSON B | Y = A == 8 | |
2 | PERSON A | Y = B > A | |
3 | PERSON E | Y = C < 0 | D(2,1) == 3 | |
4 | PERSON D | Y = A; Y(A ~= C .* 5) = -1 | |
5 | PERSON C | Y = D; Y(Y >= 3) = Y(Y >= 3) .* 20 | |
6 | PERSON B | Y = D; Y(D > 4) = 3 .* D(D > 4) | |
Functions (~10 min)
MATLAB includes a lot of built-in functions that are useful for working with data. Some functions that we’ve used so far include:
… and many others! (This is not an exhaustive list.) But sometimes you need to write your own function to do something in MATLAB. Let’s practice writing our own function.
Write an implementation of the function farmableLand.
A plot of land is considered "farmable" (i.e. able to be farmed and grow crops) if its Exchangeable Sodium Percentage (ESP) is within a certain minimum/maximum range. The function farmableLand takes in a vector of ESP measurements across a given plot of land, along with the minimum allowable ESP and the maximum allowable ESP (in this order). It returns the percentage of the plot of land that falls within the allowable ESP range, including the min/max limits (and hence is farmable). The percentage is calculated by finding all the measurements that fall within the allowable ESP range and dividing by the total number of measurements.
Here is an example of calling farmableLand with a vector of ESP measurements, a minimum ESP of 0.3 and a maximum ESP of 0.7:
>> farmableLand([0.86, 0.35, 0.41, 0.55, 0.12], 0.3, 0.7)
ans =
0.6000
The function you write must work for an input ESP vector of any size and for any min/max values for ESP. You can assume that the ESP vector will have at least one element in it, though. You are NOT allowed to use for/while loops or if statements in your code.
The Leader should start a discussion about possible ways to design this function (parameters, return variables, implementation). The Scribe should write down the group’s design plan for the function. The Googler should have Runestone Chapter 3 open and be ready to look up information about writing functions. The Coder should share their screen so everyone can see the function as you collaboratively write the function. The Questioner should write down any questions that you have for the Staff Coach.
5
Describe your group’s ideas for designing this function, including what parameters, return values, and implementation (this should NOT include code):
Write your function in the box below, including the function interface.
6
|
|
Review: Images (~5 min)
MATLAB represents color images as an array with three dimensions: row, column, layer. We often refer to the layers as “channels” when working with images.
Assume an image img, with the following values at each color channel:
Assume the following statements have been run (but DO NOT run them in MATLAB yet):
red = img(:, :, 1);
green = img(:, :, 2);
blue = img(:, :, 3);
green(20 < red & red < 50) = 0;
red(:, :) = 50;
blue(blue < 128) = 64;
blue(blue >= 128) = 255;
img(:, :, 2) = green;
img(:, :, 3) = blue;
What are the values of each color channel for img after the code has been run?
After entering your answers above, create a MATLAB script to check your answers. The Questioner should write down any questions that you have for the Staff Coach.
7
Red Channel [ 30, 64, 150; 120, 37, 70] | Green Channel [ 32, 32, 32; 128, 128, 128] | Blue Channel [ 25, 206, 89; 128, 255, 51] |
Red Channel | Green Channel | Blue Channel |
Review: Visualization
Common 2D Plots: Line plot, scatter plot, bar chart (~5 min)
Recall that MATLAB has built-in functions that may be useful in plotting data in 2D space. Here are some of the more commonly used functions:
Let’s start by considering when each of these types of plot will be the right choice for a dataset. In the table below you will be given the description of a dataset. State which function would be an appropriate visualization tool for the data and explain why.
8
Function: | Description: |
plot(x, y) | creates a 2-D line plot of the data in y versus the corresponding values in x |
scatter(x, y) | creates a scatter plot with circles at the locations specified by the vectors x and y |
bar(y) | creates a bar graph with one bar for each element in y. If y is an m-by-n matrix, then bar creates m groups of n bars |
Dataset: | Person leading discussion: | Which function should be used to visualize the data? | Justification for answer: |
The value of your GSI’s car and their number of gray hairs over the last 7 years. | A | | |
Monthly rent prices and square footage for apartments around Ann Arbor | B | | |
Number of Engr 101 students planning to major in the different departments | C | | |
Daily temperatures and visitors to the city pool over the Summer 2019 season | D | | |
Given the prompt, write the code necessary to create the appropriate plot. Work simultaneously to stay on time. Check your work with the given plot.
Note: your plots might look a little different depending on the tick values used by MATLAB for the size of your figure. That’s okay.
9
| Prompt: | Code: | Check: |
| Create a line plot that looks like a sine wave. The x values range from -10 to 10 with 200 values. The y values are the sine of x. The line width should be 4. | | |
| You have these vectors: a = [1, 2, 3, 5] b = [3, 6, 9, 4] Create a scatter plot using these two vectors. Use a marker size of 120 and a linewidth of 4. The x- and y-axes should both have limits of 0 to 10. | | |
| You have this vector: y = 2:2:18; Create a bar chart of this vector. Include these customizations:
| | |
Person E
Person D
Person B
Histograms (~10 min)
In engineering we commonly repeat experiments many times to capture more information about how accurate, precise, and repeatable our measurements are. Histograms allow us to present the frequencies of occurrences throughout a dataset in a clear and easily interpreted visual.
Let’s start by considering when a histogram will be the right choice for a dataset. In the table below you will be given the description of a dataset. Choose whether or not a Histogram would be an appropriate visualization tool for the data and explain why.
10
Dataset: | Person leading discussion: | Is a histogram appropriate? | Justification for answer: |
Customer wait times at a dentist’s office | B | | |
Old Faithful eruption heights | D | | |
Michigan counties organized by percentage of state population | A | | |
Ages of trees cut down on an acre | C | | |
Yearly revenues for 3 automakers over the last 30 years | E | | |
Now that we have a better understanding of when to use histograms, practice creating the histograms described below. Work simultaneously to stay on time. Use the data provided and paste the histogram you create as well as the code used to generate it in the table below.
11
| Prompt: | MATLAB code: | Histogram: |
| Single histogram with default bin size. | dist = randi(15, 1, 70); % TODO add your code to make a histogram of the data in the dist variable | |
| Single histogram with 35 bins. Label the x axis as “Values” and the y axis as “Occurrences.” | x = normrnd(43,2,1,150); % TODO add your code to make a histogram of the data in the x variable! | |
Person A
Person C
3D Plotting and meshgrid (~20 min)
Often, showing more than two spatial dimensions in our plots may mean a clearer visualization of the data.
Recall that MATLAB has built-in functions that may be useful in plotting data in 3D space. Here are some of the more commonly used functions:
12
Function: | Description: |
plot3(x, y, z) | plots coordinates in 3D space. To plot a set of coordinates connected by line segments, specify x, y, and z as vectors of the same length. |
scatter3(x, y, z) | displays circles at the locations specified by the vectors x, y, and z. |
[X, Y] = meshgrid(x, y) | returns 2D grid coordinates based on the coordinates contained in vectors x and y. X is a matrix where each row is a copy of x, and Y is a matrix where each column is a copy of y. The grid represented by the coordinates X and Y has length(y) rows and length(x) columns. |
surf(X, Y, Z) | creates a 3D surface plot, which is a 3D surface that has solid edge colors and solid face colors. The function plots the values in matrix Z as heights above a grid in the x-y plane defined by X and Y. The color of the surface varies according to the heights specified by Z. |
contour(Z) | creates a 2D contour plot containing the lines where Z has equal values, where Z contains height values on the x-y plane. MATLAB automatically selects the contour lines to display. The column and row indices of Z are the x and y coordinates in the plane, respectively. |
contourf(Z) | same as contour but the area between the contour lines is filled in by colors corresponding to the values of Z. |
Given the prompt, write the code necessary to create the appropriate plot. Work simultaneously to stay on time. Check your work with the given plot.
Note: your plots might look a little different depending on the tick values used by MATLAB for the size of your figure. That’s okay.
13
| Prompt: | Code: | Check: |
| Create a line plot that looks like a spiral. The z values range from 0 to 10 with 100 values. The x values are the cosine of z, and the y values are the sine of z. The line width should be 3. | | |
| You have these vectors: a = [1, 2, 3, 5] b = [3, 6, 9, 10] c = [2, 4, 6, 9] Create a 3D scatter plot using these three vectors. | | |
| Create a 3D surface such that the x range is -2 to 2, increment by 1. The y range is -3 to 3, increment by 1. The height should be the x value squared plus the y value squared. | | |
Person B
Person E
Person D
Given the prompt, write the code necessary to create the appropriate plot. Work simultaneously to stay on time. Check your work with the given plot.
Note: your plots might look a little different depending on the tick values used by MATLAB for the size of your figure. That’s okay.
14
| Prompt: | Code: | Check: |
| Create a contour plot of z where: z = abs(cos(x) + cos(y)) for all combinations of x and y. Use the starting vectors for x and y values provided. | x = linspace(-2*pi,2*pi); y = linspace(0,4*pi); % TODO add your code to make a contour plot of the data in the z variable! | |
| Create a FILLED contour plot of z where: z = abs(cos(x) + cos(y)) for all combinations of x and y. Use the starting vectors for x and y values provided. | x = linspace(-2*pi,2*pi); y = linspace(0,4*pi); % TODO add your code to make a filled contour plot of the data in the z variable! | |
Person A
Person B
Plotting Multiple Datasets (~10 min)
On the same axes: plot, scatter, and hold
Sometimes, two sets of data are most appropriately displayed on the same axis for easy comparison. In MATLAB, we can accomplish this either by providing multiple pairs of arguments to a plotting function or by using the hold function.
Practice plotting the given datasets on the same axes using the prescribed method. Work simultaneously to stay on time.
Note: your plots might look a little different depending on the tick values used by MATLAB for the size of your figure and on the data generated by the rand() function. That’s okay.
15
| Prompt: | Code: | Check: |
| Plot both datasets on the same axis using the plot function with multiple arguments. Add a legend in the top left corner labeling y1 as “Data 1” and y2 as “Data 2.” | x1 = 1:.5:50; y1 = 2:100; x2 = 1:.5:50; y2 = 25:.5:74; % TODO add your code to plot both datasets on the same axis | |
| Create a single figure containing both data sets on a single axis by utilizing the hold function. Ensure that the first dataset “val1” is marked by Xs and that there is a legend that labels the inputs as “Val1” and “Val2.” | x1 = 1:99; val1 = .25 .* rand(99,1) + .5; val2 = 0.3 .* sin(x1) + .5 ; % TODO add your code to make a figure with both graphs | |
Person C
Person D
On different axes: subplots
In some situations it is most helpful to view figures side by side to gain the most insight. Instead of creating two separate figure windows and attempting to arrange them easily, we can use the subplot function to create multiple plots in a single figure window.
Using your code from the earlier exercises, create the figures shown and paste your code in the code column. Collaboratively work together on these exercises.
16
Figure | Code |
Note: your plots might look a little different depending on the tick values used by MATLAB for the size of your figure and on the data generated by the rand() function. That’s okay. | |
17
Figure | Code |
Note: your plots might look a little different depending on the tick values used by MATLAB for the size of your figure and on the data generated by the rand() function. That’s okay. | |
Practice: Data Analysis (~25 min)
In engineering, making a convincing argument as to why your results are significant is as important as writing the computer programs and analyzing the data. This exercise is an opportunity to apply your MATLAB knowledge and coding skills to solve problems, make sense of information, and evaluate the evidence to make decisions.
Motivation
Overall enrollment at U-M generally trended up from 2000-2016. This has placed stress on existing student support resources, including building/classroom space, dorm space, tutoring services, and the availability of mental health resources such as CAPS counselors.
At the same time, Laura’s anecdotal evidence1 seems to indicate that students feel that they are expected to participate in more extracurricular activities now than when she was an undergraduate engineering student roughly 20 years ago; these extracurricular activities include participation in service organizations, project teams, Greek life, sports, research outside of class, etc. Students and companies alike may consider these extracurricular activities vital to have on a resume to help a student “stand out” from the crowd at Career Fair; therefore, the pressure to “do them all” may be intense.
However, adding extracurricular commitments, without a corresponding lessening of credit hours taken per semester, could potentially put students in an untenable “you can only pick two” situation where they have to choose between their classes, their extracurriculars, and their health. Considering the aforementioned stress on mental health support services, this is something we should be concerned about.
Research Questions
We want to investigate two research questions:
1 “anecdotal evidence” means informal information that Laura gathered just by sitting around office hours talking with students; anecdotal evidence does not represent all
18
Methods
We want to understand some enrollment trends and their meaning within the university environment. First, download the following data files from the Lab 6 folder on the google drive:
Open the files in a text editor (or spreadsheet program) and look at what data is contained in these files.
Use MATLAB to analyze this data in order to answer the research questions above. You may use whatever scripts or functions (built-in or make your own!) you wish to create to analyze this data. There are just two things required for this exercise:
You can investigate, analyze, and plot any data that you like. If you are not sure where to start, here are some suggestions for things to do:
This is a topic that we could spend an entire semester investigating, so we will do just a quick investigation today. Focus on making your two graphs and briefly interpreting the results. After you’ve finished your analysis, copy the MATLAB code and plots into the appropriate boxes on the next slides.
19
Paste your MATLAB code here:
… continue on the next page if you need more room
20
|
… continue your code here if you need more room. If you do not need more room, please type ALL DONE in this box so you won’t lose points.
21
|
Insert your lab6_1.png here:
Insert your lab6_2.png here:
22
|
|
Based upon what you’ve seen in your figures and analysis, provide an answer to the two research questions below in your group’s own words. Be sure to reference your figures and explain how they support your answers.
The College of Engineering has hired CAPS counselors specifically to work with CoE students. What other things can CoE do to help students balance classes, extracurriculars (which are the fun parts of college!!), and overall health?
23
|
|
|
Time with course staff
The Questioner is responsible for recording any questions the team has for the staff member. Make sure you write down your questions even though you're asking them out loud so that we can tell from your worksheet that the team was actively thinking of questions to ask.
Submit worksheet
Submit the lab worksheets to Gradescope by Saturday at 11:59PM. We strongly recommend submitting your worksheet the same day that you meet as a group!
The Scribe is responsible for making the final submission to Gradescope. You need to add your other group members to the submission after it is uploaded using this link:
24
Your team's question | Summary of staff answer |
| |
| |
| |
| |
| |