Code:

RSM.m

function [bb]=RSM(filename)

%read the data p l form the file name

bb=load(filename);

x=[bb.x]’;

f=[bb.f]’;

A=x.^0;

%make the matrix A

for i=1:bb.p

A=[A x.^i];

End

%solve the  Polynomial coefficients using least square method

a=A\f;

bb.coef=a;

%get the value by polyfit

f1=polyval(a(end:-1:1),x);

%make the figure using x and err

plot(x,abs(f1-f),’linewidth’,1.5);

xlabel(‘x’);

ylabel(‘err’);

%get the max err

maxerr=max(abs(f-f1));

err=abs(f-f1);

%find the index where tha max err is

[i,j]=max(abs(f-f1));

bb.maxerr=maxerr;

bb.index=j;

bb.err=err;

%save the struct with filename output.mat

save(‘output.mat’, ‘-struct’,’bb’)

test1.m

%test the code RSM,we use p=4,l=11

ss.p=4;

ss.l=41;

ss.x=[linspace(0,1,ss.l)];

ss.f=exp(-ss.x)+exp(ss.x);

save(‘input.mat’, ‘-struct’,’ss’)

[bb2]=RSM(‘input.mat’)

Analysis:

Table1:

 

Polynomial coefficients

maximum deviation

indices i

p=2

l=11

a=[ 2.0057   -0.0779    1.1513]

.7048968e-2

11

p=3

l=21

a=[ 1.9990  0.0245  0.8853  0.1763]

.1009350e-2

21

p=4

l=41

a=[ 2.0000  -0.0008   1.0058   -0.0139    0.0951]

.2918664e-4

41

When p=3, l=21

The differences between the function and the approximation is as follow figures

When p=4,l=41

The differences between the function and the approximation is as follow figures

  • from the tabel 1 the maximum deviation happens when x=1,
  • the maximum deviation will decreases as l increase and as p increases, because the ,as l increases and p increases,the step h will decreases ,so the error will decrease
  • the approximation between the points of discretization can see in Table 1,when p=2,l=11,the differences between the function and the approximationwill less than .7048968e-2, while the points outside the interval [0 1] will not as accurate as inside
  • we can se form the figures the distance is small in p=4,l=41,than p=3,l=21
  • ,when p=2,the err<0.3917,and the max err is .7048968e-2,which is consistent with the formula

p=3,l=21

x=[0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 0.7 0.75 0.8 0.85 0.9 0.95 1];

f=[2 2.0025 2.01 2.0225 2.0401 2.0628 2.0907 2.1238 2.1621 2.2059 2.2553 2.3102 2.3709 2.4376 2.5103 2.5894 2.6749 2.7671 2.8662 2.9725 3.0862];

err=[0.001 0 0.0005 0.0007 0.0006 0.0004 0.0001 0.0001 0.0004 0.0005 0.0006 0.0006 0.0004 0.0002 0.0001 0.0004 0.0006 0.0007 0.0005 0 0.001];

maxerr=.1009350e-2

Polynomial coefficients a=[ 1.9990  0.0245  0.8853  0.1763]

原文链接:matlab assignment