-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExercise1.1.R
84 lines (54 loc) · 1.39 KB
/
Exercise1.1.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#source("/Users/dgy/Desktop/SDS385/R/Exercise1.1.r")
library("Matrix");
library("microbenchmark");
InversionMethod<- function(A,b){
temp1<- solve(A);
return(temp1 %*% b);
}
QRMethod<- function(A,b){
temp1<- qr.solve(A,b);
return(temp1);
}
CholeskyMethod<- function(A,b){
R= chol(A);
temp1<- forwardsolve(t(R),b);
return(backsolve(R,temp1));
}
Simulation <- function(N,P){
X<- matrix(rnorm(N*P),nrow=N);
y<- rnorm(N);
w<- diag(rep(1,N));
temp1<-crossprod(X,w);
A<- temp1 %*% X;
b<- temp1 %*% y;
print(microbenchmark(InversionMethod(A,b)));
print(microbenchmark(CholeskyMethod(A,b)));
print(microbenchmark(QRMethod(A,b)));
}
SparseCholeskyMethod2<- function(A,b){
temp3<- expand(Cholesky(A));
R<- t(temp3$L) %*% (temp3$P);
temp4<- forwardsolve(t(R),b);
return(backsolve(R,temp4));
}
SparseCholeskyMethod<- function(A,b){
R= chol(A);
temp2<- forwardsolve(t(R),b);
return(backsolve(R,temp2));
}
SparseSimulation <- function(N,P,s){
X<- matrix(rnorm(N*P),nrow=N);
mask<- matrix(rbinom(N*P,1,s),nrow=N);
Xs<- Matrix(mask*X,sparse=T);
X<- Matrix(mask*X);
y<- Matrix(rnorm(N));
w<- diag(rep(1,N));
temp1<- t(Xs)%*%w;
As<- Matrix(temp1 %*% Xs);
temp2<- t(X)%*%w;
A<- Matrix(temp2 %*% X);
b<- Matrix(temp2 %*% y);
print(microbenchmark(InversionMethod(A,b)));
print(microbenchmark(SparseCholeskyMethod(As,b)));
print(microbenchmark(SparseCholeskyMethod(A,b)));
}