R <-> Matlab, generating correlated normal variates
HI, I need to generate correlated normal variates, with certain mean and sd.
I don't have Statistics Toolbox, so I have to code it myself.
I have a running R code from:
http://www.unt.edu/benchmarks/archives/2001/december01/rss.htm
but, cannot translate it in Matlab.
R code:
it works fine, but....
MATLAB version:
# Sample from Bivariate Normal - MATLAB
produces an error
The error point is the product:
sd*cF'
it produces in MATLAB a vector 1x2, whereas R produces a matrix 2x2.
Any comments on the vector matrix product differences would be appreciated,
MJ
PS: I don't have the Statistics Toolbox. M
HI, I need to generate correlated normal variates, with certain mean and sd.
I don't have Statistics Toolbox, so I have to code it myself.
I have a running R code from:
http://www.unt.edu/benchmarks/archives/2001/december01/rss.htm
but, cannot translate it in Matlab.
R code:
Code:
# n=sample size; p=number of columns
# u=mean of columns; s=standard deviation
# of columns; S=correlation matrix
mvrnorm <- function(n, p, u, s, S) {
Z <- matrix(rnorm(n*p), p, n)
t(u + s*t(chol(S))%*% Z)
}
# Sample from Bivariate Normal - R
z<-mvrnorm(n=100, p=2, u=c(100,100), s=c(15,15), S=matrix(c(1, .4, .4, 1), ncol=2, nrow=2,byrow=T))
MATLAB version:
Code:
% function [X,Y] = corrNormal(Npar, Nobs, mu1, mu2, sd1, sd2, rho)
% Input:
% Npar - number of correlated parameters
% Nobs - number of observations
% rho - correlation between two parameters
% Output:
% M - correlated normal distributed numbers
function M = corrNormal(Npar, Nobs, mu1, mu2, sd1, sd2, rho)
mu = [mu1,mu2];
sd = [sd1,sd2];
% create uncorrelated observations
X = randn(Npar, Nobs);
% compute cholesky factor
S = [1 rho; rho 1];
cF = chol(S);
% R code: Y = t(u + s*t(chol(S))%*% Z)
M = mu + sd*cF'*X;
end
Code:
M = corrNormal(2, 100, 10, 10, .5, .5, 0.7);
Code:
Error using +
Matrix dimensions must agree.
Error in corrNormal (line 26)
Y = mu + sd*cF'*X;
sd*cF'
it produces in MATLAB a vector 1x2, whereas R produces a matrix 2x2.
Any comments on the vector matrix product differences would be appreciated,
MJ
PS: I don't have the Statistics Toolbox. M
Last edited: