%a最小二乘拟合 % 读入数据 data = load('scrippsm.txt'); t = linspace(1996, 2010, length(data)); %…
- User
%a最小二乘拟合 % 读入数据 data = load('scrippsm.txt'); t = linspace(1996, 2010, length(data)); % 年份
% 构造矩阵A和向量b A = [ones(length(data),1) t' cos(2pit') sin(2pit')]; b = data;
% 求解最小二乘问题 x = A\b; c1 = x(1) c2 = x(2) c3 = x(3) c4 = x(4)
% 计算拟合值和RMSE f = c1 + c2t + c3cos(2pit) + c4sin(2pi*t); RMSE = sqrt(mean((f-data).^2))
% 绘图 plot(t, data, 'o', t, f, '-') xlabel('年份') ylabel('CO2浓度 (ppv)') legend('数据点', '拟合曲线')
%b预测CO2浓度 % 预测的时间点 t_predict = [2004.4, 2004.8, 2005.4, 2005.8];
% 计算拟合值和误差 f_predict = c1 + c2t_predict + c3cos(2pit_predict) + c4sin(2pi*t_predict); true_values = [380.63, 374.06, 382.45, 376.73]; errors = true_values - f_predict;
% 显示结果 fprintf('预测值\t\t实际值\t\t误差\n'); for i = 1:length(true_values) fprintf('%.4f\t\t%.4f\t\t%.4f\n', f_predict(i), true_values(i), errors(i)); end
%c 加上额外项
% 构造矩阵A和向量b A = [ones(length(data),1) t' cos(2pit') sin(2pit) cos(4pit)]; b = data;
% 求解最小二乘问题 x = A\b; c1 = x(1); c2 = x(2); c3 = x(3); c4 = x(4); c5 = x(5);
% 计算拟合值和RMSE f = c1 + c2t + c3cos(2pit) + c4sin(2pit) + c5cos(4pit); RMSE = sqrt(mean((f-data).^2));
% 绘图 plot(t, data, 'o', t, f, '-') xlabel('年份') ylabel('CO2浓度 (ppv)') legend('数据点', '拟合曲线') 以上代码出现 错误使用 horzcat 要串联的数组的维度不一致。
出错 nihe2 (第 47 行) A = [ones(length(data),1) t' cos(2pit') sin(2pit) cos(4pit)];
- Assistant
这个错误提示可能是因为向量 t 与 cos(4pit) 维度不一致造成的。可以尝试将 t 用 linspace 重新生成,保证维度一致。
修改后的代码如下:
%c 加上额外项
% 重新生成时间向量 t = linspace(1996, 2010, length(data));
% 构造矩阵A和向量b A = [ones(length(data),1) t' cos(2pit') sin(2pit') cos(4pit')]; b = data;
% 求解最小二乘问题 x = A\b; c1 = x(1); c2 = x(2); c3 = x(3); c4 = x(4); c5 = x(5);
% 计算拟合值和RMSE f = c1 + c2t + c3cos(2pit) + c4sin(2pit) + c5cos(4pit); RMSE = sqrt(mean((f-data).^2));
% 绘图 plot(t, data, 'o', t, f, '-') xlabel('年份') ylabel('CO2浓度 (ppv)') legend('数据点', '拟合曲线')