Michi

Michi commited on 2012-06-10 14:06:22
Zeige 1 geänderte Dateien mit 35 Einfügungen und 8 Löschungen.

... ...
@@ -1,13 +1,13 @@
1 1
 #Problem 1
2 2
 
3 3
 #definition of a straight line function
4
-y=function(x,m,b) m*x+b
4
+linrel=function(x,m,b) m*x+b
5 5
 
6 6
 #definition x-Vctor
7 7
 x_vec=seq(-1,3,0.1)
8 8
 
9 9
 #definition y-vector
10
-y_vec=y(x_vec,1,0)
10
+y_vec=linrel(x_vec,1,0)
11 11
 #plotting x-vector vs. y-vector
12 12
 plot(x_vec, y_vec, type="l", col="black", xlab='x',ylab='f(x)=y')
13 13
 
... ...
@@ -20,12 +20,39 @@ points(x_vec_2,mock_vec, col="red", type="p")
20 20
 
21 21
 ##Problem2
22 22
 conrel =function(b) b
23
-linrel =function(x,m,b) m*x+b
24 23
 quarel =function(x,a,m,b) a*x**2 + m*x+b
25 24
 
26 25
 reso = 10  #the resolution
27
-a_val = seq(-4,4,reso)
28
-m_val = seq(-4,8,reso)
29
-b_val = seq(-2,2,reso)
30
-
31
-
26
+a_vec = seq(-4,4,length.out = reso)
27
+m_vec = seq(-4,8,length.out = reso)
28
+b_vec = seq(-2,2,length.out = reso)
29
+
30
+
31
+# Define function chi2_quad
32
+chi2_qua = function(a,m,b) sum((mock_vec - quarel(mock_vec,a,m,b))**2/(0.4)**2)
33
+chi2_lin = function(m,b) sum((mock_vec - linrel(mock_vec,m,b))**2/(0.4)**2)
34
+chi2_con = function(b) sum((mock_vec - conrel(b))**2/(0.4)**2)
35
+
36
+# Calculate 3-dim grid for values a=-4..4, m=-4..8, b-2..2
37
+qua_arr = array(NA, dim=c(length(b_vec),length(m_vec),length(a_vec)))
38
+lin_arr = array(NA, dim=c(length(b_vec),length(m_vec)))
39
+con_arr = array(NA, dim=c(length(b_vec)))
40
+for (i in (1:length(b_vec))){
41
+    con_arr[i] = chi2_con(b_vec[i])
42
+	for (j in (1:length(m_vec))){
43
+        lin_arr[i,j] = chi2_lin(m_vec[j],b_vec[i])
44
+		for (k in (1:length(a_vec))){
45
+			qua_arr[i,j,k] = chi2_qua(a_vec[k],m_vec[j],b_vec[i])
46
+		}
47
+	}
48
+}
49
+
50
+minimum_qua=min(qua_arr)
51
+best_m_qua = m_vec[which(qua_arr == minimum_qua,arr.ind=TRUE)[2]]
52
+best_b_qua = b_vec[which(qua_arr == minimum_qua,arr.ind=TRUE)[1]]
53
+best_a_qua = a_vec[which(qua_arr == minimum_qua,arr.ind=TRUE)[3]]
54
+minimum_lin=min(lin_arr)
55
+best_m_lin = m_vec[which(lin_arr == minimum_lin,arr.ind=TRUE)[2]]
56
+best_b_lin = b_vec[which(lin_arr == minimum_lin,arr.ind=TRUE)[1]]
57
+minimum_con=min(lin_arr)
58
+best_b_con = b_vec[which(con_arr == minimum_con,arr.ind=TRUE)[1]]
32 59