Efficient R code can plot theoretical concepts for a multivariate normal density. Below outlines the procedure.
Download
Let's start by downloading two main packages in R Studio
Plots 3D
```{r warning=FALSE}
install.packages("plot3D")
library(plot3D)
```
Computes multivariate normal densities
```{r warning=FALSE}
install.packages("mvtnorm")
library(mvtnorm)
```
Now, to set up our grid-2D we can create a range of values of x1 and x2
```{r warning=FALSE}
x1 = seq(-pi/4, pi/4, len=30)
x2 = seq(pi/4,3*pi/4, len=30)
```
This is because the normal density varies from -3 to 3, approximately
The next step is to form two 2D functions to get a 3D plot
```{r warning=FALSE}
f.function = function(x1,x2){cos(x1*x2)}
h.function = function(x1,x2){1-((pi*x1)^2)/8}
```
Now we can use "persp3D" and "outer".
They are part of the previously downloaded package
Plot in 3D
```{r warning=FALSE}
zf.function = outer(x1,x2,f.function )
zh.function = outer(x1,x2,h.function )
```
This is to organize the plots in a matrix view
```{r warning=FALSE}
par(mfrow = c(1,2))
```
color surface of f is red color surface of h is blue
```{r warning=FALSE}
persp3D(x1,x2,zf.function,col = "red", main="f function surface")
persp3D(x1,x2,zh.function,col = "blue", main="h function surface")
```
*.rmd linguist-language=R *
FOR 2D
Here is the Theory:
The pdf for a bi-variate 2D or (p=2) normal density at a point
Were the second order Taylor expansion for f(x) around the point
so, to find each term of Taylor expansion, we work with this equation
when
and our bivariate equation is
for the first term of Taylor expansion
for the second term of Taylor expansion
we will see below
Expanding terms from right to left:
by definition of symmetry,
and
It looks like
so our function is
the gradient is formed by
If we do
then
similarly for
for x=u
for the third term of Taylor expansion
We have to find
when
for
when
Also by symmetry,
In
Then the second order Taylor expansion for f(x) around the point
is of the form