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.