Search code examples
matlabcovariancegaussian

[matlab]Creating Random Gaussian variables using covariance matrix


[(Workspace)][1]I created random variables using covariance Matrix. I want to generate 300 random two dimensional feature data (length & weight) of each specie ω1 (salmon) and ω 2(bass). Salmon (ω 1): mean: 65 cm, 22 kg covariance: [20 0.1; 0.1 70] Sea bass (ω 2): mean : 80 cm, 31 kg covariance: [40 5; 5 50] After I created Samples, I computed covariance Matrix again just to check out. But I found it totally wrong from the original covariance matrix. Can somebody help me out please? Attached is my code and different result. Please Help Me :(


Solution

  • I believe you might be creating the wrong data, try creating it this way:

    % 0. INITILIZATION
    clc, clear all, close all
    rng default  % For reproducibility
    N = 200; %Number of samples
    
    % 1. Data info
    mu1 = [65 22]';
    mu2 = [80 31]';
    mu = [mu1 mu2];
    covar1 = [20 0.1;0.1 70];
    covar2 = [40 5;5 50];
    
    % Data generation
    Dset1 = mvnrnd(mu1,covar1,N)';
    Dset2 = mvnrnd(mu2,covar2,N)';
    figure('name', 'Data set X and X'''), hold on
    
    % Plot the data
    plot(Dset1(1,:),Dset1(2,:), 'b.',Dset2(1,:),Dset2(2,:), 'r.')
    

    Also, if you want to check if the data has indeed the proper covariance, use a bigger N, say 5000 for example.