I’ve been doing some experiments where I need to account for a correction in material refractive index. Fortunately, my PI has those refractive indices from his own experiments, but I wanted to see how some data from from the 50’s hold up. Those values weren’t in my proportions and needed some interpolating to figure out. I opted for the programmatic approach because of how many data points I needed.

I wrote a linear interpolator in MATLAB, listed below. The program takes in an array of independent variable values (xcol), an array of the dependent variable values (ycol), and then an array of the independent variable values of interest (x). The output is an array with the corresponding interpolated dependent value. The program works by incrementing up the xcol array until the x value is less than the next xcol value. It then uses the linear interpolation equation to calculate the corresponding y. Finally, the script repeats for each term in x. Some lines have been commented out where a “verbose” mode narrates the program actions. It’ll extrapolate based on the first or last two points as appropriate but it won’t warn you it’s doing so.

This can and probably will be improved upon in the future, with features such as extrapolation warnings, array size mismatch error handling, and an actual verbose mode trigger, but I’m sharing it as is under the GNU GPLv3 license.

```%
%function y = linearInterpolate(xcol, ycol, x)
%
%Author: Jakub Konkol
%Created: November 30, 2019
%
%Function:      linearInterpolate
%
%Description:   Given a column of x-values and y-values, the function will
%perform a linear interpolation or extrapolation for a x-value of interest.
%Will accept a 1D array of x-values and perform an interpolation for each
%value.
%
%Parameters:    xcol    - 1D array of independent values
%               ycol    - 1D array of dependent values
%               x       - 1D array of independent values of interest
%
%Return:        an array with the interpolated y values

function y = linearInterpolate(xcol, ycol, x)
y = zeros(length(x),1);
for i = 1:length(x)
%fprintf('Working on %.1f\n', x(i))
j=1;
%disp(j)
while x(i) > xcol(j+1) && j+1  xcol(j) && j < length(xcol)))
end
y(i) = ycol(j) + (x(i)-xcol(j)) * (ycol(j+1)-ycol(j))/(xcol(j+1)-xcol(j));
%fprintf('The x value %.4f is between %.4f and %.4f, corresponding to y values %.4f and %.4f\n', x(i), xcol(j), xcol(j+1), ycol(j), ycol(j+1))
end
end
```