# TODO: Add comment
# 
# Author: E.Korsching 18.11.2011
###############################################################################



linfit.ab <- function(x,y){
	# linear fit based on least square estimation
	#  ssq in y - therefore x, y can not be switched !
	xbar <- mean(x)
	ybar <- mean(y)
	
#	co.var.xy <- sum((x-xbar)*(y-ybar))		#empiric covariance of xy
#	var.x <- sum((x-xbar)^2)				#empiric variance of x
	
	b <- sum((x-xbar)*(y-ybar))/sum((x-xbar)^2)			# estimator for b (slope)
	a <- ybar-b*xbar									# estimator for a (intercept)
	ei <- y-a-b*x										# estimator for the theoretical residuals
	
#	ei : Abstände von der Fitgeraden zum Originalwert - von der Fitgeraden aus gesehen bzgl. Vorzeichen (- nach unten, + nach oben)
	return(list(a=a,b=b,ssq=sum(ei^2),ei=ei))	#intercept, slope, ssq, vector of distances
}


# Vertauschung von x y gibt unterschiedliche Ergebnisse - Abhänigkeiten beachten!

#aax=c(10,20,30,40)	#x
#aay=c(2,4,8,8)		#y
#aa3 <- linfit.ab(x=aax,y=aay)	# intercept 0     slope 0.22   ssq 2.8    distance fit line to point  -0.2 -0.4  1.4 -0.8
#aa4 <- linfit.ab(x=aay,y=aax)	# intercept 2.59  slope 4.07   ssq 51.8   distance fit line to point  -0.7  1.1 -5.2  4.8
#aa5 <- lm(aax~aay)$coefficients	# intercept 2.593        aa2 4.074
#aa6 <- lm(aay~aax)$coefficients	# intercept -8.882 e-16  aa2 0.22

#plot(x=aax,y=aay,xlim=c(0,50),ylim=c(0,10))
#abline(a=aa3[[1]],b=aa3[[2]])	#a:intercept, b:slope
##abline(a=aa6[1],b=aa6[2])		#a:intercept, b:slope  identisch zu aa3

#plot(x=aay,y=aax,xlim=c(0,10),ylim=c(0,50))
#abline(a=aa4[[1]],b=aa4[[2]])	#a:intercept, b:slope


