# Octave 代码解决方案 ## 1. 多项式拟合 cos(x) 函数 ```octave % 定义x范围 x = linspace(0, 2*pi, 100); y_true = cos(x); % 准备绘图 figure; hold on; plot(x, y_true, 'k-', 'LineWidth', 2, 'DisplayName', 'True cos(x)'); % 2阶多项式拟合 p2 = polyfit(x, y_true, 2); y2 = polyval(p2, x); plot(x, y2, 'r--', 'DisplayName', '2nd order'); % 3阶多项式拟合 p3 = polyfit(x, y_true, 3); y3 = polyval(p3, x); plot(x, y3, 'g--', 'DisplayName', '3rd order'); % 4阶多项式拟合 p4 = polyfit(x, y_true, 4); y4 = polyval(p4, x); plot(x, y4, 'b--', 'DisplayName', '4th order'); % 6阶多项式拟合 p6 = polyfit(x, y_true, 6); y6 = polyval(p6, x); plot(x, y6, 'm--', 'DisplayName', '6th order'); % 图表装饰 legend('Location', 'best'); title('Polynomial Fits to cos(x)'); xlabel('x'); ylabel('y'); grid on; hold off; ``` 注意事项: 1. 高阶多项式在边界可能出现较大偏差(龙格现象) 2. 多项式阶数越高,拟合曲线震荡越明显 3. 对于周期性函数,傅里叶级数可能比多项式更合适 ## 2. 位移和速度数据处理 ```octave % 给定数据 t = [0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0]; v = [0, 0.4794, 0.815, 0.9975, 0.9093, 0.5985, 0.1411]; s = [1, 1.5, 2, 2.5, 3, 3.5, 4]; % 绘制速度和位移随时间变化 figure; subplot(2,1,1); plot(t, v, 'bo-'); title('Velocity vs Time'); xlabel('Time (s)'); ylabel('Velocity (m/s)'); grid on; subplot(2,1,2); plot(t, s, 'ro-'); title('Displacement vs Time'); xlabel('Time (s)'); ylabel('Displacement (m)'); grid on; % 计算加速度(数值微分) dt = diff(t); dv = diff(v); a = dv ./ dt; % 绘制加速度 figure; plot(t(1:end-1), a, 'go-'); title('Acceleration vs Time'); xlabel('Time (s)'); ylabel('Acceleration (m/s^2)'); grid on; ``` 注意事项: 1. 数值微分对数据噪声敏感,可能需要平滑处理 2. 时间间隔不均匀时,微分计算需要调整 3. 位移数据看起来是线性增长,可能与速度数据不完全对应 ## 3. 二维插值比较 ```octave % 定义函数 f = @(x,y) x.^2/16 - y.^2/9; % 创建网格 [x, y] = meshgrid(linspace(-3, 3, 10)); z = f(x, y); % 创建更密的网格用于插值 [xi, yi] = meshgrid(linspace(-3, 3, 50)); % 最近邻插值 zi_nn = interp2(x, y, z, xi, yi, 'nearest'); % 双线性插值 zi_linear = interp2(x, y, z, xi, yi, 'linear'); % 三次样条插值 zi_spline = interp2(x, y, z, xi, yi, 'spline'); % 立方插值 zi_cubic = interp2(x, y, z, xi, yi, 'cubic'); % 绘制结果 figure; subplot(2,2,1); surf(xi, yi, zi_nn); title('Nearest Neighbor'); zlim([-1 1]); subplot(2,2,2); surf(xi, yi, zi_linear); title('Bilinear'); zlim([-1 1]); subplot(2,2,3); surf(xi, yi, zi_spline); title('Spline'); zlim([-1 1]); subplot(2,2,4); surf(xi, yi, zi_cubic); title('Cubic'); zlim([-1 1]); % 真实函数对比 zt_true = f(xi, yi); figure; surf(xi, yi, zt_true); title('True Function'); zlim([-1 1]); ``` 注意事项: 1. 不同插值方法在边界处的表现差异较大 2. 三次样条插值可能产生过冲现象 3. 数据点稀疏时,高阶插值方法可能产生伪影 [2025-03-27 11:02:18 | AI写代码神器 | 1160点数解答]