The main commands for this section are polyfit, polyval and interp1. Let’s begin with linear regression.
Example 9.1.1: Linear Regression
Plot a set of data:
The data certainly seems to have a (downward) linear trend. We can find the line of best fit as follows:
The command polyfit returns the matrix [-2.4857 12.7143] of the slope and y-intercept of the line of best fit. The y values of this line correspond-
ing to x (from 0 to 5) are stored in the variable besty. We plot them together using:
We often use regression lines to guess y values for x values that are not included in the data set. For this, we use interpolation.
Example 9.1.2: Interpolation
Using the data from example 38, we would like to know the y value corresponding to the x value 3.5. For this, we use the command interp1 (that’s the number one on the end, not a lowercase for the letter L).
We plot these together with the interpolated point indicated with a red tri-
Note that if you try to use the interp1 function for data that is outside the data set, you will get an error since you are trying to “extrapolate” instead of interpolate.
This indicates that the answer is NaN or “Not a Number” (look it up in the Help files).