############################ SOLUTIONS ##############################


# Solution to Problem 1


A = matrix(c(1, 0, -4, -2, 2, 5, 1, -8, 9), nrow=3, ncol=3)
b = c(0, 8, -9)
x = solve(A, b); x
# Or, less efficiently, form A-inverse
Ainv = solve(A)       # solve() with one parameter gives inverse
Ainv %*% b             # Gives the same x
A %*% x                # As a check, should give b


# Solution to Problem 2


H2 = matrix(c(1,2,2,3), 2, 2); H2
H2 = H2^(-1); H2  # Gives elementwise inverse, not matrix inverse
solve(H2)  # The inverse has integer elements
H2a = round(H2, 2); H2a
solve(H2a) # Not very close
# If you do the same with H3, it will be much worse. Try it!
# The rest has more advanced material.
H6 = matrix(0, ncol=6, nrow=6)
for (i in 1:6) for (j in 1:6) H6[i,j] = 1/(i+j-1)
H6
solve(H6)  # Looks nice with integers, but try options(digits=15)
# Here I show how a function can be defined and used
# This time I use the outer sum of two vectors. Check help(outer)
hilbert = function(n) {
  H = outer(1:n, 1:n, "+") - 1
  H^(-1)
}
hilbert(7)
H7 = hilbert(7)
solve(H7)
# cleaning up
rm(list=ls())


# Solution to Problem 3


# Key data in with 
y = scan()
mean(y); median(y); var(y); sd(y); range(y)
boxplot(y, boxwex=0.4, col="gray80")
hist(y)
qqnorm(y, datax=TRUE)
qqline(y, datax=TRUE)


# Solution to problem 4


# Here is an example using the t-distribution.
# Remember that the t-distribution looks like the normal distribution, 
# but with heavier tails.
# First a small sample of 20:
x = rt(20,3)
hist(x)
qqnorm(x); qqline(x) 
# Maybe you will see a bit of deviation from a normal distribution,
# but usually this is hard to see for small samples.
# A larger sample of 200:
x = rt(200,3)
hist(x)
qqnorm(x); qqline(x) 
# Definitely this deviates from normality
# Cleaning up
rm(list=ls())
