% (1) 计算原始函数值 x = 0:1:4 * pi; y = exp(-x/5) .* sin(x); % (2) 利用interp1插值函数求解插值 xi =…
- User
% (1) 计算原始函数值 x = 0:1:4 * pi; y = exp(-x/5) .* sin(x);
% (2) 利用interp1插值函数求解插值 xi = linspace(0, 4 * pi, 1000); % 更细的插值点网格 yi_nearest = interp1(x, y, xi, 'nearest'); yi_linear = interp1(x, y, xi, 'linear'); yi_spline = interp1(x, y, xi, 'spline'); yi_pchip = interp1(x, y, xi, 'pchip');
% (3) 利用yw=interp1(x,y,xw,'spline','extrap')求外插值 xw = 4 * pi + 1; yw = interp1(x, y, xw, 'spline', 'extrap');
% (4) 绘图 figure; plot(x, y, 'o-', 'DisplayName', '原始数值'); hold on; plot(xi, yi_nearest, ':', 'DisplayName', 'Nearest 插值'); plot(xi, yi_linear, '--', 'DisplayName', 'Linear 插值'); plot(xi, yi_spline, '-.', 'DisplayName', 'Spline 插值'); plot(xi, yi_pchip, '-', 'DisplayName', 'PCHIP 插值'); plot(xw, yw, 'r*', 'DisplayName', 'Spline 外插值', 'MarkerSize', 10); xlabel('x 值'); ylabel('y 值'); title('不同插值方法的比较'); legend('Location', 'best'); grid on; hold off; 更改代码里的变量名称!
- Assistant
% (1) Calculate the original function values x_values = 0:1:4 * pi; y_values = exp(-x_values/5) .* sin(x_values);
% (2) Use interp1 function to interpolate interp_x_values = linspace(0, 4 * pi, 1000); % Finer interpolation points grid yi_nearest = interp1(x_values, y_values, interp_x_values, 'nearest'); yi_linear = interp1(x_values, y_values, interp_x_values, 'linear'); yi_spline = interp1(x_values, y_values, interp_x_values, 'spline'); yi_pchip = interp1(x_values, y_values, interp_x_values, 'pchip');
% (3) Use yw=interp1(x,y,xw,'spline','extrap') to obtain extrapolated value extrap_x_value = 4 * pi + 1; extrap_y_value = interp1(x_values, y_values, extrap_x_value, 'spline', 'extrap');
% (4) Plot the results figure; plot(x_values, y_values, 'o-', 'DisplayName', 'Original Numerical'); hold on; plot(interp_x_values, yi_nearest, ':', 'DisplayName', 'Nearest Interpolation'); plot(interp_x_values, yi_linear, '--', 'DisplayName', 'Linear Interpolation'); plot(interp_x_values, yi_spline, '-.', 'DisplayName', 'Spline Interpolation'); plot(interp_x_values, yi_pchip, '-', 'DisplayName', 'PCHIP Interpolation'); plot(extrap_x_value, extrap_y_value, 'r*', 'DisplayName', 'Spline Extrapolation', 'MarkerSize', 10); xlabel('x values'); ylabel('y values'); title('Comparison of Different Interpolation Methods'); legend('Location', 'best'); grid on; hold off;