// Least Squares Demonstrator // Click on a point to drag, click elsewhere to add a point //set some flags show_resids=0; show_squares=0; show_lsq=0; show_mover=0; show_ellipse=0; x1=50; x2=82; y1=85;y2=100; // initial data from height and weight ht=[44,52,59,65,78,80]; wt=[75,95,90,100,99,113]; oldht=ht; oldwt=wt; n = nrow(ht); // Graphics Window with Script NewWindow("Least Squares", vlistbox( Hlistbox( g=Graph(FrameSize(300,300),XScale(25,100),yScale(60,130),Double Buffer, mh = mean(ht); //mean x mw = mean(wt); //mean y sh = StdDev(ht); //standard deviation x sw = StdDev(wt); //standard deviation y means = matrix({{mh,mw}}); stds = matrix({{sh,sw}}); n = nrow(ht); //number of data points cor = (ht-mh)`*(wt-mw)/sh/sw/(n-1); //correlation coefficient lsqm=cor*sw/sh; //least squares slope lsqb=mw-lsqm*mh; //least squares intercept moverm=(y2-y1)/(x2-x1); moverb=y2-moverm*x2; preds=lsqm*ht+lsqb; //matrix of ols predicted values resids=preds-wt; sqresids=resids`*resids; if(show_squares, fill color(8); for(i=1, i<=n, i++, Rect(ht[i],wt[i],ht[i]+abs(wt[i]-preds[i]),preds[i],3) ); ); if(show_resids, pencolor(4); for(i=1, i<=n, i++, Vline(ht[i],wt[i],preds[i]) ); pencolor(0) ); if(show_lsq, pen color(3); YFunction(lsqm*x+lsqb,x); pen color(0) ); if(show_mover, pencolor(6); Yfunction(moverm*x+moverb,x); Handle(x1,y1,x1=x;y1=y); Handle(x2,y2,x2=x;y2=y); pen color(0) ); DragMarker(ht,wt); if(show_ellipse, NormalContour(.9,means,stds,matrix({cor})); text({60,70},"corr=",char(cor,4,2)); ); MouseTrap({},oldht=ht; oldwt=wt; ht=ht|/matrix({x});wt=wt|/matrix({y})) )), Hlistbox( buttonbox("LS Line",if(show_lsq,show_lsq=0,show_lsq=1); g << reshow;), buttonbox("LS Residuals",if(show_resids,show_resids=0,show_resids=1; show_lsq=1); g << reshow;), buttonbox("LS Squares",if(show_squares,show_squares=0,show_squares=1; show_lsq=1); g << reshow;) ), HListBox( buttonbox("Correlation Ellipse",if(show_ellipse,show_ellipse=0,show_ellipse=1); g << reshow;), buttonbox("Delete Last Point",ht=oldht;wt=oldwt; g << reshow;) ) ) ); 0