在Matlab中使用指定数量的独立Bernoulli + -1非零项创建稀疏矩阵

时间:2014-07-31 19:55:13

标签: matlab

如何在Matlab中我们可以形成一个矩阵X,1000 by 1000,稀疏,例如,

5% of independent Bernoulli +-1 nonzero entries?

即。这样的矩阵会有rho = ||X||_0/10^6 = 0.05.

2 个答案:

答案 0 :(得分:1)

随机选择5%的元素

n = numel(X);
ind = randi(n, round(.05*n), 1);

使用随机变量

分配这些元素
X(ind) = binornd(1, .5, length(ind), 1) *2-1;

查看binornd's documentation了解详情。

为避免重复的randi号码,您可以使用统计工具箱中的randsample,或this post中提及的randperm之类的内容。 / em>的


修改

ind = [];
t0 = round(.05*n);
t1 = length(ind);
while t1 < t0
    ind(end+1:t0) = randi(n, t0-t1, 1);
    ind = unique(ind);
    t1 = length(ind);
end

答案 1 :(得分:1)

如果您需要将矩阵构建为sparse (in Matlab's sense)

M = 1000; %// number of rows
N = 1000; %// number of columns
perc = 5/100; %// percentage (fraction) of +/-1 entries

n = round(M*N*perc); %// compute number of nonzero entries
nz = 2*(rand(1,n)<.5)-1; %// generate nonzero entries: +/-1 with .5 probability
ind = randsample(M*N,n); %// choose linear indices of nonzero entries
X = sparse(ind, 1 ,nz , M*N, 1, n); %// build matrix as linearized
X = reshape(X,M,N); %// put into shape