clear all; clc; p=[0 500 2000 5000]; q=[1e-5 1.15e-5 1.8e-5 4.0e-5]; x_1=0:5000; a(:,1)=x_1; k1=interp1(p,q,abs(x_1),'linear'); a(:,2)=k1; [m,n]=find(a(:,1)==300|a(:,1)==1500|a(:,1)==3000); a1=a(m,2); subplot(3,1,1); plot(x_1,k1); title('一维线性插值'); x_2=0:5000; Lagrange(p,q,x_2); L=Lagrange(p,q,x_2); b=[L(301),L(1501),L(3001)]; y0=1:5000; yy=Zuixiao(p,q,y0); c=[yy(1,300),yy(1,1500),yy(1,3000)]; % *** 拉格朗日插值 *** function L = Lagrange(x,y,x_2) L = zeros(1,length(x_2)); for i = 1:1:length(x_2) l = ones(1,length(x)); for k = 1:1:length(x) for j= 1:1:length(x) if j ~= k l(k) = l(k) * ( x_2(i)-x(j)) / (x(k)-x(j)); end end L(i) = L(i) + l(k)*y(k); end end if nargout == 0 subplot(3,1,2); plot(x_2,L); title('拉格朗日插值'); end end % *** 最小二乘法 *** function yy=Zuixiao(x,y,y0) R(:,1)=x.^2; R(:,2)=x; R(:,3)=[1 1 1 1]; Y=y'; a=(R'*R)^-1*R'*Y; yy=a(1).*(y0.*y0)+a(2).*y0+a(3); subplot(3,1,3); plot(y0,yy); title('最小二乘法'); end我应该如何修改这段代码才能让三条曲线画在同一个图中
时间: 2023-09-06 17:11:29 浏览: 107
你可以将三条曲线的绘制放在同一个 subplot 中,具体修改如下:
```matlab
clear all; clc;
p=[0 500 2000 5000];
q=[1e-5 1.15e-5 1.8e-5 4.0e-5];
x_1=0:5000;
a(:,1)=x_1;
k1=interp1(p,q,abs(x_1),'linear');
a(:,2)=k1;
[m,n]=find(a(:,1)==300|a(:,1)==1500|a(:,1)==3000);
a1=a(m,2);
x_2=0:5000;
L=Lagrange(p,q,x_2);
b=[L(301),L(1501),L(3001)];
yy=Zuixiao(p,q,x_2);
c=[yy(1,300),yy(1,1500),yy(1,3000)];
subplot(1,3,1:3); % 修改subplot
plot(x_1,k1);
hold on; % 添加hold on
plot(x_2,L);
plot(x_2,yy);
legend('一维线性插值','拉格朗日插值','最小二乘法'); % 添加图例
title('插值方法比较');
% *** 拉格朗日插值 ***
function L = Lagrange(x,y,x_2)
L = zeros(1,length(x_2));
for i = 1:1:length(x_2)
l = ones(1,length(x));
for k = 1:1:length(x)
for j= 1:1:length(x)
if j ~= k
l(k) = l(k) * ( x_2(i)-x(j)) / (x(k)-x(j));
end
end
L(i) = L(i) + l(k)*y(k);
end
end
end
% *** 最小二乘法 ***
function yy=Zuixiao(x,y,y0)
R(:,1)=x.^2;
R(:,2)=x;
R(:,3)=[1 1 1 1];
Y=y';
a=(R'*R)^-1*R'*Y;
yy=a(1).*(y0.*y0)+a(2).*y0+a(3);
end
```
修改后的代码会将三条曲线画在同一个图中,且添加了图例说明。
阅读全文