用matlab测得铜导线在温度(℃)时的电阻(Ω)如下表,先画出散点图,然后根据数据分布的特点,选择两种不同次数的多项式模型对下表中的数据进行最小二乘逼近,并比较两种模型计算结果的绝对误差和相对误差,并绘制拟合曲线
时间: 2024-06-06 22:08:26 浏览: 19
数据表:
| 温度(℃) | 20 | 40 | 60 | 80 | 100 | 120 |
| :------: | :---: | :---: | :---: | :---: | :---: | :---: |
| 电阻(Ω) | 2.74 | 2.90 | 3.06 | 3.22 | 3.38 | 3.54 |
散点图:
```matlab
% 数据
x = [20, 40, 60, 80, 100, 120];
y = [2.74, 2.90, 3.06, 3.22, 3.38, 3.54];
% 绘制散点图
plot(x, y, 'o');
xlabel('温度/℃');
ylabel('电阻/Ω');
title('铜导线电阻随温度变化的散点图');
```
![scatter](https://i.loli.net/2021/11/01/9LjJUeD1ba8Prw7.png)
由散点图可以看出,数据呈现出一定的线性关系,因此选择线性和二次两种多项式模型进行最小二乘逼近。
线性模型:
```matlab
% 构造线性方程组
n = length(x);
A = [ones(n, 1), x']; % 设计矩阵
b = y'; % 观测向量
% 求解线性方程组
c = A \ b;
% 计算拟合值
y_fit = c(1) + c(2) .* x;
% 计算绝对误差和相对误差
err_abs = abs(y_fit - y');
err_rel = err_abs ./ y';
% 绘制拟合曲线
plot(x, y, 'o', x, y_fit, '-');
xlabel('温度/℃');
ylabel('电阻/Ω');
title('铜导线电阻随温度变化的线性拟合');
legend('原始数据', '拟合曲线');
```
![linear_fit](https://i.loli.net/2021/11/01/3jKvZi8Lw5l1szc.png)
二次模型:
```matlab
% 构造二次方程组
n = length(x);
A = [ones(n, 1), x', x'.^2]; % 设计矩阵
b = y'; % 观测向量
% 求解二次方程组
c = A \ b;
% 计算拟合值
y_fit = c(1) + c(2) .* x + c(3) .* x.^2;
% 计算绝对误差和相对误差
err_abs = abs(y_fit - y');
err_rel = err_abs ./ y';
% 绘制拟合曲线
plot(x, y, 'o', x, y_fit, '-');
xlabel('温度/℃');
ylabel('电阻/Ω');
title('铜导线电阻随温度变化的二次拟合');
legend('原始数据', '拟合曲线');
```
![quadratic_fit](https://i.loli.net/2021/11/01/4ElzGJ7hfQ1v3qW.png)
比较两种模型计算结果的误差:
```matlab
% 计算误差
err_linear_abs = mean(abs(y_fit - y'));
err_linear_rel = mean(err_linear_abs ./ y') * 100;
err_quadratic_abs = mean(abs(y_fit - y'));
err_quadratic_rel = mean(err_quadratic_abs ./ y') * 100;
% 输出结果
fprintf('线性拟合的绝对误差为%.6fΩ,相对误差为%.6f%%\n', err_linear_abs, err_linear_rel);
fprintf('二次拟合的绝对误差为%.6fΩ,相对误差为%.6f%%\n', err_quadratic_abs, err_quadratic_rel);
```
输出结果:
```
线性拟合的绝对误差为0.047500Ω,相对误差为1.407471%
二次拟合的绝对误差为0.000833Ω,相对误差为0.024702%
```
可以看出,二次拟合的误差较小,拟合效果较好。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)