Search code examples
matlabmatlab-figure

How can I have a positive covariance between two variables in matlab?


I want to make the plot of a two variable function, but this function has some parameters that I need to calculate initially. Specifically, these parameters are two random variables, that they follow a bivaraite normal distribution and they are correlated. What I need, for my purposes, is a postivive covariance between these two variables. Is there any chance that I could make a loop or whatever to obtain a pistive covariance always? My effort is the following

X=normrnd(3,0.25,2);
Y=normrnd(9,0.4,2);
covar=cov(X,Y);

but the covariances are negative and i need to many times to fins a case where there are postitive. Of course I can change the meand and the standard deviation, but I would like something more stable, that will keep the covariance pistive and provide my work. I thought about the command exprnd(mu,sz), but it does not solve my problem.


Solution

  • You can use the built-in matlab function mvnrnd (mulivariate-normal-random numbers) to generate these data. This function comes in very useful.

    mu = [0, 0];               % means of the distributions samples are drawn from
    sigma = [1, 0.6; 0.6, 1];  % covariance of distributions (eye(2) for uncorrelated)
    n = 25
    
    [bivariate_data] = mvnrnd(mu, sigma, n);
    

    https://www.mathworks.com/help/stats/mvnrnd.html#d122e544190

    EDIT:

    Sigma is a covariance matrix where the diagonal is the variance of each distribution and the off-diagonals are the covariance between the two distributions (i.e. [var(variable1), covar(variable1, variable2), var(variable2); covar(variable1, variable2).

    You can check this in matlab as the off-diagonals must be the same, but the diagonals dont have to be. As such the 2x2 identity matrix (eye(2) in matlab) [1, 0; 0, 1] specifices two distributions with equal variance and zero covariance. Alternatively, ones(2) would be maximum covariance. It is interesting to see what happends if you try to specify a [1, 2; 2, 1], some further discussion can be found https://stats.stackexchange.com/questions/69114/why-does-correlation-matrix-need-to-be-positive-semi-definite-and-what-does-it-m/69117.