为什么我的随机生成的协方差矩阵的 Matlab 代码没有生成正定矩阵?



这是我的代码。当我使用chol(V)时,我得到了一个错误,即V不是正定的。我认为通过构造它一定是肯定的。知道哪里出错了吗?

% I want 10000 draws of a 5x1 multivariate normal distribution
N =5;
T = 10000;
% randomly generate standard deviations
sigma = 1 + .1*rand(N,1);
% randomly generate correlations which are between [-1,1]
rho = -1+2*rand(nchoosek(N,2),1);
% This grabs the indices of the elements in the lower triangle below the main diagonal
% itril comes from https://www.mathworks.com/matlabcentral/fileexchange/23391-triangular-and-diagonal-indexing
I = itril(N,-1);
% Initialize correlation matrix
corr = zeros(N);
% Fill in lower triangle of correlation matrix with generated correlations
corr(I) = rho;
% make correlation matrix symmetric with 1s on diagonal
corr = corr+corr'+eye(N);
% Variance matrix is sigma_i*sigma_j*corr(i,j)
V = (sigma*sigma').*corr;
% means vector
mu = rand(N,1);
% generate multivariate normal draws
e = mu' + randn(T,N)*chol(V);

这不是创建关联矩阵的方法。仅仅因为你的矩阵是对称的,对角线上的值是1对角线上的值在-1到1之间并不意味着它是一个相关矩阵。例如,你创建矩阵的方式,你可以在随机变量X1和X2之间有相关性+1,在X2和X3之间有相关性+1,在X1和X3之间有相关性-1,如果矩阵条目来自"real"之间的相关性,这显然是不可能的;随机变量。因此,也不能保证这样生成的矩阵是正(半)定的。

您应该生成一些矩阵X,其中包含随机变量之间的(线性)依赖关系,然后您的协方差矩阵简单地为X' * X(或X * X'取决于您如何排序X)。

最新更新