# Category Archives: MATLAB

## This week in screencasting: The polar express

It’s been a little quiet on the screencasting front lately, but in the next couple of weeks my colleague teaching Calculus III will be hitting material for which I volunteered to provide some content: namely, using MATLAB to visualize some of the surfaces and solids used in multiple integration. Yesterday, I finished two of these. The first on is on polar coordinates and polar function plotting in MATLAB:

And the second one is on cylindrical coordinates and plotting two-variable functions in cylindrical coordinates:

MATLAB doesn’t provide a built-in function for plotting in cylindrical coordinates. Instead — and this is either ingenious or annoying depending on how you look at it — to plot something in cylindrical coordinates, you generate all the points you need in cylindrical coordinates and then use the pol2cart function to convert them en masse to cartesian coordinates, then plot the whole thing as usual in cartesian coordinates.

I think this is smart, since by avoiding the use of a specialized function for cylindrical plots and sticking instead to a single command for 3D plotting, you learn one command for all 3D plots and you get to use all the extras available, such as adding a contour plot onto the cylindrical plot. Overloading the pol2cart function so that it can accept and produce the third coordinate makes this all work. Overall I like how MATLAB doesn’t try to make a function for everything but rather creates a well-featured set of relatively simple tools that will do lots of things.

But I can see where some people — especially MATLAB novices — would find all this annoying, since the entire process takes several steps. There’s a workflow diagram for doing this in the screencast, but a better way is to make an M-file that holds all the steps. Here’s the one I flashed briefly at the end of the screencast:

```
% Script for plotting a cylindrical function.
% Written by Robert Talbert, Ph.D., 10/20/2010

% Theta: Change t1 and t2 to set the starting and ending values for theta.
t1 = 0;
t2 = pi/2;
theta = linspace(t1, t2);

% r: : Change r1 and r2 to set the starting and ending values for theta.
r1 = -5;
r2 = 5;
r = linspace(r1, r2);

% Create meshgrid for inputs:
[theta, r] = meshgrid(theta, r);

% Apply the function to create a matrix of z-values. Change the function to
% match what you want to plot.

z = r*cos(theta);

% Convert to cartesian and plot using mesh:

[x,y,z] = pol2cart(theta, r, z);
mesh(x,y,z)
```

It would be simple enough to modify this so that it’s a function rather than a script, accepting the arrays theta and r and a function handle for z, and then producing the 3D plot. Or, one could even make an “ez” version where the user just enters a string containing the function s/he wants. If somebody wants to try that out, and you want to share your results, just put the source code in the comments.

The third one in this series will be up later this weekend. It’s on spherical coordinates and it’s pretty much the same process, only using sph2cart instead of pol2cart. There might be a fourth one as well, dealing with some special cases like constant cylindrical/spherical functions (you can’t just say “rho = 5”, because rho has to be a matrix) and how to plot not just the surfaces but the volumes underneath them.

Comments Off on This week in screencasting: The polar express

Filed under Calculus, Engineering, Math, MATLAB, Teaching, Technology

## This week in screencasting: Contour plots in MATLAB

By my count, this past week I produced and posted 22 different screencasts to YouTube! Almost all of those are short instructional videos for our calculus students taking Mastery Exams on precalculus material. But I did make two more MATLAB-oriented screencasts, like last week. These focus on creating contour plots in MATLAB.

Here’s Part 1:

And Part 2:

I found this topic really interesting and fun to screencast about. Contour plots are so useful and simple to understand — anybody who’s ever hiked or camped has probably used one, in the form of a topographical map — and it was fun to explore the eight (!) different commands that MATLAB has for producing them, each command producing a map that fits a different kind of need. There may be even more commands for contour maps that I’m missing.

I probably won’t match this week’s output next week, as I’ll be on the road in Madison, WI on Monday and Tuesday and there are several faculty meetings in the run-up to the start of the semester. But at the very least, I need to go back and do another two-variable function plot screencast because I inexplicably left off surface plots and the EZMESH and EZSURF commands on last week’s screencasts.

Comments Off on This week in screencasting: Contour plots in MATLAB

Filed under Calculus, Educational technology, Math, MATLAB, Screencasts, Technology

## The semester in review

Image via Wikipedia

I’ve made it to the end of another semester. Classes ended on Friday, and we have final exams this coming week. It’s been a long and full semester, as you can see by the relative lack of posting going on here since around October. How did things go?

Well, first of all I had a record course load this time around — four different courses, one of which was the MATLAB course that was brand new and outside my main discipline; plus an independent study that was more like an undergraduate research project, and so it required almost as much prep time from me as a regular course.

The Functions and Models class (formerly known as Pre-calculus) has been one of my favorites to teach here, and this class was no exception. We do precalculus a bit differently here, focusing on using functions as data modeling tools, so the main meat of the course is simply looking at data and asking, Are the data linear? If not, are they best fit by a logarithmic, exponential, or power function? Or a polynomial? And what should be the degree of that polynomial? And so on. I enjoy this class because it’s primed for the kind of studio teaching that I’ve come to enjoy. I just bring in some data I’ve found, or which the students have collected, and we play with the data. And these are mainly students who, by virtue of having placed below calculus on our placement exam, have been used to a dry, lecture-oriented math environment, and it’s very cool to see them light up and have fun with math for a change. It was a small class (seven students) and we had fun and learned a lot.

The Calculus class was challenging, as you can tell from my boxplots posts (first post, second post). The grades in the class were nowhere near where I wanted them to be, nor for the students (I hope). I think every instructor is going to have a class every now and then where this happens, and the challenge is to find the lesson to learn and then learn them. If you read those two boxplots posts, you can see some of the lessons and information that I’ve gleaned, and in the fall when I teach two sections of this course there could be some significant changes with respect to getting more active work into the class and more passive work outside the class.

Linear Algebra was a delight. This year we increased the credit load of this class from three hours to four, and the extra hour a week has really transformed what we can do with the course. I had a big class of 15 students (that’s big for us), many of whom are as sharp as you’ll find among undergraduates, and all of whom possess a keen sense of humor and a strong work ethic that makes learning a difficult subject quite doable. I’ll be posting later about their application projects and poster session, which were both terrific.

Computer Tools for Problem Solving (aka the MATLAB course) was a tale of two halves of the semester. The first half of the semester was quite a struggle — against a relatively low comfort level around technology with the students and against the students’ expectations for my teaching. But I tried to listen to the students, giving them weekly questionnaires about how the class is going, and engaging in an ongoing dialogue about what we could be doing better. We made some changes to the course on the fly that didn’t dumb the course down but which made the learning objectives and expectations a lot clearer, and they responded extremely well. By the end of the course, I daresay they were having fun with MATLAB. And more importantly, I was receiving reports from my colleagues that those students were using MATLAB spontaneously to do tasks in those courses. That was the main goal of the course for me — get students to the point where they are comfortable and fluent enough with MATLAB that they’ll pull it up and use it effectively without being told to do so. There are some changes I need to make to next year’s offering of the course, but I’m glad to see that the students were able to come out of the course doing what I wanted them to do.

The independent study on finite fields and applications was quite a trip. Andrew Newman, the young man doing the study with me, is one of the brightest young mathematicians with whom I’ve worked in my whole career, and he took on the project with both hands from the very beginning. The idea was to read through parts of Mullen and Mummert to get basic background in finite field theory; then narrow down his reading to a particular application; then dive in deep to that application. Washington’s book on elliptic curves ended up being the primary text, though, and Andrew ended up studying elliptic curve cryptography and the Diffie-Hellman decision problem. Every independent study has a creative project requirement attached, and his was to implement the decision problem in Sage. He’s currently writing up a paper on his research and we hope to get it published in Mathematics Exchange. (Disclaimer: I’m on the editorial board of Math Exchange.) In the middle of the semester, Andrew found out that he’d been accepted into the summer REU on mathematical cryptology at Northern Kentucky University/University of Cincinnati, and he’ll be heading out there in a few weeks to study (probably) multivariate public-key systems for the summer. I’m extremely proud of Andrew and what he’s been able to do this semester — he certainly knows a lot more about finite fields and elliptic curve crypto than I do now.

In between all the teaching, here are some other things I was able to do:

• Went to the ICTCM in Chicago and presented a couple of papers. Here’s the Prezi for the MATLAB course presentation. Both of those papers are currently being written up for publication in the conference proceedings.
• Helped with hosting the Indiana MAA spring meetings at our place, and I finished up my three-year term as Student Activities Coordinator by putting together this year’s Indiana College Mathematics Competition.
• Did a little consulting work, which I can’t really talk about thanks to the NDA I signed.
• I got a new Macbook Pro thanks to my college’s generous technology grant system. Of course Apple refreshed the Macbook Pro lineup mere weeks later, but them’s the breaks.
• I’m sure there’s more, but I’ve got finals on the brain right now.

In another post I’ll talk about what’s coming up for me this summer and look ahead to the fall.

Comments Off on The semester in review

## Boxplots: Curiouser and curiouser

The calculus class took their third (and last) hour-long assessment yesterday. In the spirit of data analytics ala the previous post here, I made boxplots for the different sections of the test (Conceptual Knowledge (CK), Computation (C), and Problem Solving (PS)) as well as the overall scores. Here are the boxplots for this assessment — put side-by-side with the boxplots for the same sections on the previous assessments. “A2” and “A3” mean Assessments 2 and 3.

Obviously there is still a great deal of improvement to be had here — the fact that the class average is still below passing remains unacceptable to me — but there have been some definite gains, particularly in the conceptual knowledge department.

What changed between Assessment 2 and Assessment 3? At least three things:

• The content changed. Assessment 2 was over derivative rules and applications; Assessment 3 covered integration.
• The way I treated the content in class changed. Based on the results of Assessment 2, I realized I needed to make conceptual work a much greater part of the class meetings. Previously the class meetings had been about half lecture, with time set aside to work “problems” — meaning, exercises, such as “find the critical numbers of $y = xe^{-x}$. Those are not really problems that assess conceptual knowledge. So I began to fold in more group work problems that ask students to reason from something other than a calculation. I stressed these problems from the textbook more in class. I tried to include more such problems in WeBWorK assignments — though there are precious few of them to be had.
• The level of lip service I gave to conceptual problems went up hugely. Every day I was reminding the students of the low scores on Conceptual Knowledge on the test and that the simplest way to boost their grades in the class would be to improve their conceptual knowledge. I did not let their attention leave this issue.

Somewhere in a combination of these three things we have the real reason those scores went up. I tend to think the first point had little to do with it. Integration doesn’t seem inherently any easier to understand conceptually than differentiation, particularly at this stage in the course when differentiation is relatively familiar and integration is brand new. So I think that simply doing more conceptual problems in class and stressing the importance of conceptual knowledge in class were the main cause of the improvements.

Quite interestingly, the students’ scores on computation also improved — despite the reduced presence of computation in class because of the ramped-up levels of conceptual problems. We did fewer computational problems on the board and in group work, and yet their performance on raw computation improved! Again, I don’t think integration is easier than differentiation at this stage in the course, so I don’t think this improvement was because the material got easier. Maybe the last test put the fear of God into them and they started working outside of class more. I don’t know. But this does indicate to me that skill in computation is not strictly proportional to the amount of computation I do, or anybody else does, in class.

To overgeneralize for a second: Increased repetition on conceptual problems improves performance on those problems dramatically, while the corresponding reduction in time spent on computational exercises not only does not harm students’ performance on computation but might actually have something to do with improving it. If we math teachers can understand the implications of this possibility (or at least understand the extent to which this statement is true) we might be on to something big.

The scores on problem solving went two different directions. On the one hand, the median went up; but on the other hand the mean went down. And the middle 50% didn’t get any better on the top end and got worse on the bottom end. I’m still parsing that out. It could be the content itself this time; most of the actual problems in integration tend to take place near the end of the chapter, after the Fundamental Theorem and u-substitution, so the kinds of problems in this section were less than a week old for these students. But quite possibly the improvement in conceptual knowledge brought the median up on problem solving, despite the newness of the problems. Or maybe the differences aren’t even statistically significant.

What I take away from this is that if you want students to do well on non-routine problems, those problems have to occupy a central place in the class, and they have to be done not outside of class where there’s no domain expert to guide the students through them but in class. And likewise, we need not worry so much that we are “wasting precious class time” on group work on conceptual problems at the expense of individual computation skill. Students might do just fine on that stuff regardless, perhaps even better if they have enhanced conceptual understanding to support their computational skills.

It all goes back to support the inverted classroom model which I’ve been using in the MATLAB course, and now I’m wondering about its potential in calculus as well.

## MATLAB as a handout creator

One of the fringe benefits of having immersed myself in MATLAB for the last year (in preparation for teaching the Computer Tools for Problem Solving course) is that I’ve learned that MATLAB is an excellent all-purpose tool for preparing materials for my math classes. Here’s an example of something I just finished for a class tomorrow that I’m really pleased with.

I was needing to create a sequence of scatterplots of data for a handout in my Functions and Models class. The data are supposed to have varying degrees of linearity — some perfect/almost perfectly linear, some less so, some totally nonlinear — and having different directions, and the students are supposed to look at the data and rank the correlation coefficients in order of smallest to largest. (This is a standard activity in a statistics class as well.)

I could have just made up data with the right shape on Excel or hand-drawn the scatter plots, but whenever I do that, it looks made it up — not with the randomness that a real set of data, even if it’s strongly linear, would have. So instead, I thought I would take a basic linear function and throw varying degrees of noise into it to make it less linear.

I wrote this little function to generate noise:

```function n = noise(degree, size)
n = degree*cos(2*pi*rand(1,size));
```

This just creates a vector of specified length (“size”) centered roughly around 0, and the bigger “degree” is the more wildly the numbers vary. (I’m sure there’s some built-in way to do this in MATLAB, but it probably took less time to write the function than it would have taken for me, the MATLAB neophyte, to look it up.)

Then I just made four linear functions and literally added in the noise for each, as well as a fifth function that was just spitting out 25 random numbers and a sixth that was a pure linear function with no noise. Then plot all of those in a 2×3 subplot. Here’s the code:

```x = 1:25;
y_bigneg = -3*x+90 + noise(5,25);
y_smallneg = -5*x + 100 + noise(30,25);
y_bigpos = 3*x + 3 + noise(3,25);
y_smallpos = 3*x + 3 + noise(10,25);
subplot(2,3,1), scatter(x, y_bigpos)
subplot(2,3,2), scatter(x, y_smallneg)
subplot(2,3,3), scatter(x, y_smallpos)
subplot(2,3,4), scatter(x, y_bigneg)
subplot(2,3,5), scatter(x, rand(1,25))
subplot(2,3,6), scatter(x, 90-4*x)
```

Here’s the result, after going in and adding titles and removing the legends in the Plot Tools window:

That can then be saved as a PDF and embedded into a $\LaTeX$ document or just posted directly to Moodle for students to play with. All of that code above could easily be compacted into one big M-file with some modifications to let the user control the number of points and whatever else.

This is basic stuff, but it’s awfully handy for creating professional-looking documents and graphics for teaching mathematics. That’s an area where I’m finding MATLAB is highly underrated.

1 Comment

Filed under Calculus, Math, MATLAB, Problem Solving, Teaching, Technology

## Analyze, hack, create

One of these days I’ll get back to blogging about the mathematics courses I teach, which make up the vast majority of my work, but the MATLAB course continues to be the place where I am working the hardest, struggling the most, learning the biggest lessons about teaching, and finally having the greatest sense of reward. This week was particularly rewarding because I think I finally figured out a winning formula for teaching a large portion of this stuff.

This was the last in a three-week series on introduction to programming. We had worked with FOR loops already. I had planned to look at WHILE loops in the same week as FOR loops, then have the students play around with branching structures in week 2, then have them apply it to writing programs to do numerical integration week 3 for use in their Calculus II class in which most of the class is currently enrolled. But the FOR loop stuff went very roughly. So I moved the numerical integration stuff up a week and saved the entire remainder of looping and branching structures — WHILE loops, the IF-ELSEIF-ELSE structure, and SWITCH — for week 3.

I approached it like this.

The majority of their homework consisted of watching three videos: one on general programming in MATLAB, another on MATLAB loop structures in general, and a third on IF and SWITCH statements. That’s about 20 minutes of straight viewing; I told the students to budget an hour for these, since they’ll want to pause and rewind and work alongside the videos. Then, the majority of their homework was this M-file:

```%% Script M-file for April 5 Prep/HW for CMP 150.
%
% For each block of code below, write a clear, English paragraph that
% explains what the code does. You can play with each block of code by
% removing the comment symbols and running this file. (You can "uncomment"
% lines by deleting the percent symbol or by highlighting the code you want
% and selecting Text > Uncomment from the menu above.)

%% Code example 1

x = input('Please enter in a number less than 100: ');
while x < 100
disp(x)
x = 2*x - 1;
end

%% Code example 2

x = input('Please enter in a number: ');
if x>=0
y = sqrt(x)
else
y = exp(x) - 1
end

%% Code example 3

value = input('Please enter in a whole number between 1 and 20: ');
switch value
case {2, 3, 5, 7, 11, 13, 17, 19}
disp('Your input is a prime number.')
case {1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20}
disp('Your input is a composite number.')
otherwise
disp('I do not think you entered in a whole number between 1 and 20.')
end
```

In other words: Here’s a bunch of code. Write up a plain-English description of what everything is doing. That was their homework. (Here’s the full assignment.)

Then in class, we played a game. For each code sample, I asked, “What if I entered [fill in the blank] to this bit of code?” For example, for code sample #1, what would happen if I entered in 100? One student immediately said, “Nothing”. Another said “It would give you a ‘0’ because that’s what ‘100 < 100’ returns as in MATLAB.” Then I had them close their eyes. “How many say, ‘Nothing’?” Count the hands that go up. “How many say ‘0’?” Count those hands. Put the tally on the board. The result: 7 for “nothing”, 6 for “zero”. Instant discussion fodder.

(By the way, this would have been a perfect place for clickers. I’m working on that.)

Next I asked, “What would happen in code sample 1 if I put in a negative number?” One guy said: “I know! I did that, and the thing kept running and never stopped, and I had to unplug my computer!” So I showed them all Control-C; then asked, “Why did that [the failure of the program to stop] happen?” In no time at all — a high-order discussion about an important related topic to looping structures (avoiding infinite loops) that I had not even planned to bring up.

We played that game for 20 more minutes. Students were into it. They were coming up with their own cases. We tried entering in ‘Hi mom’ to code sample #1 and it actually gave something back. It was mysterious and entertaining and nerdy. They discovered that testing out extreme cases is not only important for understanding your code, it’s fun. And it was a lot better than lecturing.

The best thing is, when I got them finally into their lab problems, they were asking better questions. “I think I can do this program with a SWITCH statement, but could I make it better with an IF statement?” And: “I’ve got all the cases listed out here in my SWITCH statement, but I wonder if I could just use a vector or LINSPACE to list them out instead.

So that’s going to be my approach from here on:

1. Analyze: Look at someone else’s code and write out a complete, plain-English description of what every part of it is doing.
2. Hack: Take the same code and modify it, tweak it, rewrite it, throw extreme cases at it. This is the bridge between reading code and writing code.
3. Create: Write some code to do something new — now that you’ve learned the language from someone else’s use of it.

For all I know I could be totally reinventing 40-50 years of established best practices in computer science pedagogy. But it’s pretty exciting nonetheless.

Filed under Education, MATLAB, Problem Solving, Teaching, Technology

## The MATLAB class at midterm: Comfort level

To end the first half of the semester in the MATLAB course, I gave students a lengthier-than-usual survey about the course — a sort of mid-semester course evaluation. I have a load of interesting data to sift through and analyze, relating to various aspects of the course and tagged with metadata about gender, GPA, major, whether they live on or off campus, and so on. I hope to finish analyzing the data before the semester is over. (Ba-dum-ching.)

One of the questions I asked was a mirror of a question I asked in the beginning: On a scale of 0 (lowest) to 10 (highest), rate your personal comfort level with using computers to do the kinds of things we do in this class. I’m thinking that there are affective issues about working with computers, and especially MATLAB, that are never discussed but which play a huge factor in student learning. (We seem to just tell engineers to suck it up and get to work, and assume that all MATLAB learners are engineers.) Here are the data, such as they are, for this question during the first week and at mid-term:

For some reason there were three students who didn’t respond to the midterm survey at all (it was worth 5 out of 15 points on week 7’s homework). I don’t know if the “4” and the two “8”‘s from week 1 that are missing from week 7 are the ones who didn’t respond to the survey; or if the “4” is now a “6” and one of the previous “6” people didn’t respond; or what.

Of course the striking thing here is that nothing has changed. I consider this a win on two levels.

1. The course has, at the very least, not made students generally less comfortable with using computers, which I think is pretty positive considering the subject matter and audience here.
2. The kinds of things we are doing with MATLAB have gotten progressively more complicated through the semester, so holding steady on comfort level while progressing in complexity is pretty much the same as progressing in comfort level. If you report the same comfort level after learning how to drive on the interstate as you did when first learning how to drive, period, it means that you’re more comfortable with driving in general than you used to be.

Comments Off on The MATLAB class at midterm: Comfort level

Filed under MATLAB, Teaching, Technology