- function [xx, yy] = mySplinePlot(x, y, accuracyFactor)
- % Sort the points by increasing x-coordinates
- [x ind] = sort(x);
- y = y(ind);
- % Plot the original points
- subplot(2,2,1)
- plot(x,y,'ro')
- hold on
- title('mySplinePlot')
- % Find the number of points based on the max difference between x-values
- % and create an xx vector of this number of points, evenly spaced. The max
- % difference between adjacent points should be rounded up, as should the
- % result after applying the accuracy factor.
- pointsPerInterval = round((round(max(diff(x)))) .* accuracyFactor);
- totalPoints = (length(x)-1)*pointsPerInterval + length(x);
- xx = linspace(x(1), x(end), totalPoints);
- % Interpolate to find a yy vector using the Lagrange Interpolation
- % Polynomial. Initialize yy at the right size for improved efficiency.
- yy = zeros(1,totalPoints);
- for i = 1:totalPoints
- yy(i) = lagrangeInterp(x, y, xx(i));
- end
- % Plot the vectors just calculated.
- plot(xx, yy)
- hold off
- % Call Matlab's spline and plot it as described in the problem statement
- splineYY = spline(x, y, xx);
- subplot(2,2,2)
- hold on
- plot(x,y,'ro')
- plot(xx, splineYY)
- title('spline')
- hold off
- % Make a plot as described in the problem statement and as shown in the
- % solution figures comparing mySplinePlot with spline
- subplot(2,1,2)
- plot(xx, yy, 'r')
- hold on
- plot(xx, splineYY, 'k--')
- legend('mySplinePlot','spline')
- title('mySplinePlot vs. spline')
- plot(x,y,'ro')
- hold off
- end
- % This function performs the actual Lagrange Interpolation, returning an
- % interpolated y-value for a single given x-value. Do NOT change this
- % function header.
- function interpY = lagrangeInterp(x, y, interpX)
- % Initialize interpY and determine the number of terms in the product The
- % new interpolated Y value will then be increased based on the requirements
- % of the Lagrange Interpolation.
- interpY = 0;
- n = length(x);
- % Make an estimation for each known x-coordinate using the formula given.
- for i = 1:n
- % If this makes more sense to you in a for loop, you can include a
- % nested for loop here. This is where the actual product from the
- % Lagrange Interpolation formula comes in.
- product = prod(interpX - [x(1:i-1), x(i+1:end)])/prod(x(i) - [x(1:i-1), x(i+1:end)]);
- % Update the total for interpY based on the value found for the ith
- % coordinate
- interpY = interpY + product * y(i);
- end
- end