Problem 24

mu <- matrix( c(1, 2), ncol = 1)

s <- matrix(c(1,1,1,2), nrow= 2)


mu_Y <- mu[1,1]

# VAR(Z) = E(ZZ^T) - E(Z)E(Z)^T --> E(ZZ^T) = VAR(Z) + E(Z)E(Z)^T

mu_t <- t(mu)

var_z <- s[2,2]

E_t <-  mu%*%mu_t

E_t
##      [,1] [,2]
## [1,]    1    2
## [2,]    2    4
E_Z2 <- var_z + E_t[2,2]




cov_YZ <- s[1,2]


# COV(Y,Z) = E(YZ)-E(Y)E(Z) --> E(YZ)= COV(Y,Z) + E(Y)E(Z)

E_YZ <- cov_YZ + s[2,1]
library("mvtnorm")

set.seed(666)

sample <- rmvnorm(500, mean = mu , sigma = s)

par(pty="s")

plot(sample, pch = "*", xlab = "" , ylab = "", xlim = c(-3,6) , ylim = c(-3,6))

library("fields")
## Lade nötiges Paket: spam
## Warning: Paket 'spam' wurde unter R Version 4.1.2 erstellt
## Spam version 2.8-0 (2022-01-05) is loaded.
## Type 'help( Spam)' or 'demo( spam)' for a short introduction 
## and overview of this package.
## Help for individual functions is also obtained by adding the
## suffix '.spam' to the function name, e.g. 'help( chol.spam)'.
## 
## Attache Paket: 'spam'
## Das folgende Objekt ist maskiert 'package:mvtnorm':
## 
##     rmvnorm
## Die folgenden Objekte sind maskiert von 'package:base':
## 
##     backsolve, forwardsolve
## Lade nötiges Paket: viridis
## Lade nötiges Paket: viridisLite
## 
## Try help(fields) to get started.
Sigma <-  array( c(1,2,2,5), c(2,2))

x_1 <- seq(-5, to=7, length=100)
x_2 <- seq(-5, to=7, length=100)

grid <- expand.grid(x_1,x_2)
densgrid <- dmvnorm( grid, mean = mu , sigma = Sigma)


dens <- matrix(densgrid, length(x_1), length(x_2))

image(x_1, x_2, dens, col=tim.colors())

par(mfrow = c(1,2))

y= seq(-7 , 7 , by= 0.1)



Y = dnorm(y, mean = 2 , sd= sqrt(2))

plot(Y, type = "l")

hist(Y , xaxt= "n")

# Marginal Distribution
#Assignment not clear
# creating several symetrical v/cov matrices.



s2 <- matrix(c(2,-1,-1,2), nrow= 2)

s3 <- matrix(c(4,2,2,3), nrow= 2)

s4 <- matrix(c(3,1,1,6), nrow= 2)

s5 <- matrix(c(3,-2,-2,2), nrow= 2)

s6 <- matrix(c(4,1,1,1), nrow= 2)



set.seed(666)


par(pty="s")
par(mfrow = c(2,3))




sample2 <- rmvnorm(500, mean = mu , sigma = s2)
sample3 <- rmvnorm(500, mean = mu , sigma = s3)
sample4 <- rmvnorm(500, mean = mu , sigma = s4)
sample5 <- rmvnorm(500, mean = mu , sigma = s5)
sample6 <- rmvnorm(500, mean = mu , sigma = s6)


plot(sample, pch = "*", xlab = "" , ylab = "", main = "sample 1", xlim = c(-3,6) , ylim = c(-3,6))
plot(sample2, pch = "*", xlab = "" , ylab = "", main = "sample 2", xlim = c(-3,6) , ylim = c(-3,6))
plot(sample3, pch = "*", xlab = "" , ylab = "", main = "sample 3", xlim = c(-3,6) , ylim = c(-3,6))
plot(sample4, pch = "*", xlab = "" , ylab = "", main = "sample 4", xlim = c(-3,6) , ylim = c(-3,6))
plot(sample5, pch = "*", xlab = "" , ylab = "", main = "sample 5", xlim = c(-3,6) , ylim = c(-3,6))
plot(sample6, pch = "*", xlab = "" , ylab = "", main = "sample 6", xlim = c(-3,6) , ylim = c(-3,6))