% Class 7 % Coded by NFR on 2.5.19 % Piecewise Interpolation % clc close all t = [0 20 40 56 68 80 84 96 104 110]; v = [0 20 20 38 80 80 100 100 125 125]; tvec = linspace(0,110,1000); % Linear Interpolation subplot(2,2,1) plot(t,v,'o') hold on v_vec = interp1(t,v,tvec,'linear'); plot(tvec,v_vec) % Nearest Interpolation subplot(2,2,2) plot(t,v,'o') hold on v_vec = interp1(t,v,tvec,'nearest'); plot(tvec,v_vec) % Spline Interpolation subplot(2,2,3) plot(t,v,'o') hold on v_vec = interp1(t,v,tvec,'spline'); plot(tvec,v_vec) % Pchip Interpolation subplot(2,2,4) plot(t,v,'o') hold on v_vec = interp1(t,v,tvec,'pchip'); plot(tvec,v_vec) % Quick example of 2 dimensional interpolation Time = [1 2 3 4]; % Hours Sugar = [2.2 3.4 5 7]; % Cups of sugar Modulus = [3 5 8 9;4 7 10 12; 5 9 13 15;... 6 10 14 18]; % measure of hardness % What is the modulus of a cake that is 2.5 hr and 4.2 cups sugar? Mod_Solve = interp2(Time, Sugar, Modulus, 2.5, 4.2,'cubic') % SPLINES % Let's use the t and v data sets again % What is the velocity at t = 87 using splines V_ans = spline(t,v,87) % Plot on the pchip plot plot(87,V_ans,'k+') % Example 18.12 from the book Func_1 = @(t) sin(t).^2; xvec = linspace(0,2*pi,8); yvec = Func_1(xvec); figure fplot(Func_1,[0 2*pi]) hold on plot(xvec,yvec,'o') % Part (a) cubic spline with not-a-knot conditions xq = linspace(0, 2*pi,1000); yq = spline(xvec,yvec,xq); plot(xq,yq,'k-') % Part (b) cubic spline + clamped end conditions % Exact slope at beginning and end are zeros d1 = @(t) 2*sin(t)*cos(t); slopestart = d1(0); slopeend = d1(2*pi); yvec2 = [slopestart yvec slopeend]; yq_2 = spline(xvec,yvec2,xq); plot(xq,yq_2,'g-') % Examples of contour and surface plots F2 = @(x,y) sin(x).*tan(y)./x.^2; % '.' are used for element wise notation xvec = linspace(1,2,200); yvec = linspace(.5,1,100); [xmat, ymat] = meshgrid(xvec,yvec); Z = F2(xmat,ymat); figure contourf(xvec,yvec,Z) % Add a label textstring = '\leftarrow this is an arrow'; text(1.5,.8,textstring) % Output the plot as an image saveas(gcf,'Output.png') % Draw lines on a plot line([1.2 1.2] ,[0.5 1]) figure surf(xvec,yvec,Z) % % Here is a copy of 18.12 solution from 2017 class % Practice with 18.12 from the book % F1 = @(x) sin(x).^2; xp = linspace(0,2*pi,8); yp = F1(xp); % Part a, use the default 'not-a-knot' condition for the spline xq = linspace(0,2*pi,1000); yq = spline(xp,yp,xq); plot(xp,yp,'o',xq,yq,':') hold on fplot(F1,[0 2*pi]) % Part b where we 'clamp' the ends d1 = @(t) 2*sin(t)*cos(t); slopestart = d1(0); slopeend = d1(2*pi); yp_clamp = [slopestart yp slopeend]; yq_clamp = spline(xp,yp_clamp,xq); figure plot(xp,yp,'o',xq,yq_clamp,':') hold on fplot(F1,[0 2*pi]) % Part c - use pchip for the interpolation yq_pchip = pchip(xp,yp,xq); figure plot(xp,yp,'o',xq,yq_pchip,':') hold on fplot(F1,[0 2*pi])