MATLAB Answers

# R code to matlab, or simply generating a zero mean gaussian and finding the covariance matrix

13 views (last 30 days)
Samah Salha on 24 Feb 2021
Commented: Samah Salha on 26 Feb 2021
I have the following code in R that finds the covariance matrix for the (bivariate) random vector [Generate 5,000 samples of a zero-mean Gaussian rv 𝑥 ∼ 𝑁(0,1)Then, generate the second rv 𝑦 by the equation 𝑦 = 0.5𝑥 + 𝑣 where 𝑣 ∼ 𝑁(0,0.3).] I would like to do same in Matlab, How?
x=norm(5000,0,1)
y=norm(5000,0,0.3)
y=0.5*x+v
cov=mean(x*y)-(mean(x)*mean(y))
cov
s=cov*(sqrt(var(x)))*(sqrt(var(y)))
c=matrix(c(var(x),s,s,var(y)),nrow=2)
c
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Accepted Answer

Jeff Miller on 24 Feb 2021
x=normrnd(0,1,5000,1);
v=normrnd(0,0.3,5000,1);
y=0.5*x+v;
cov=mean(x.*y)-(mean(x)*mean(y));
cov
s=cov*(sqrt(var(x)))*(sqrt(var(y)))
c= [var(x) s; s var(y)];
c
##### 1 CommentShowHide None
Samah Salha on 26 Feb 2021
Thanks!

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!