Here is the pseudo code for Chapter 5, on least squares. I wrote in Matlab. You can just cut and paste this into the command window. Or save it as a .m file.

% One iteration of the Monte Carlo Method is below:

% We do this to generate a random-ish data set.

A=1;

B=0.5;

C=0.25;

w=-3+(3-(-3)).*rand(10,1) % this is code for generating ten (a vector) of random unifor variables between [-3,3]

Data=zeros(1,10) % getting an empty vector to collect our resulting Data's

for i=1:10 % this loop fills up the Data vector with values from the poly and random var

Y(i)=A+B*(i)+C*(i)^2+w(i);

end

Data

plot(Data,'o','MarkerFaceColor','g')

%%%%% Now we fit a model to the data we just generated %%%%%%%%%%%

Amin=0;Amax=3;Bmin=0;Bmax=2;Cmin=0;Cmax=1;

cat=10000000000;

ABC=[0,0,0]

x=[1 2 3 4 5 6 7 8 9 10];

for A=Amin:0.1:Amax

for B=Bmin:0.05:Bmax

for C=Cmin:0.025:Cmax

Data=[3.638342118359073 5.434751622453716 2.511920897761036 9.480255136834117 10.544155477352458 10.585242429996457 15.420989313202291 21.281289115229903 28.495041012605785 33.789331211195659];

lsq=sum(Data-(A+B*x+C*x.^2)).^2

if lsq

cat=lsq

end

end

end

end

ABC

plot(Data,'o','MarkerFaceColor','r')

hold on;

plot(ABC(1)+ABC(2)*x+ABC(3)*x.^2,'-k')

hold on;

plot(1+0.5*x+0.25*x.^2,'--b')

WOAH! Doesn't get much cooler than that.

ReplyDelete