MATLAB - 创建psudorandom稀疏矩阵

时间:2015-02-12 19:56:14

标签: matlab matrix

是否有一种简单的方法可以制作具有特定数量非零条目的“随机”稀疏矩阵?

这是我的尝试:

r = randperm(n,m) % n = size of matrix, m = number of nonzeros in each column
H = sparse(r, r,1,n,n);

但是矩阵H在每列中没有完全非零的非零值。例如,如果我使用它来制作一个100 x 100矩阵,每列中有10个非零,那么只有10个列恰好有10个1。

我确信有一种简单的方法可以做到这一点,但我看不到它。

2 个答案:

答案 0 :(得分:3)

这将生成一个100-by-100矩阵,每列只有10 1个:

n = 100;
m = 10;
nonzerosPerColumn = repmat(m, 1, n);
%%// Build vector of linear indices to nonzero entries
pos = cell2mat(arrayfun(@(i)randperm(n,nonzerosPerColumn(i))+(i-1)*n,1:n,'uni',0));
%%// Generate the matrix
M = reshape(sparse(pos,1,1,n*n,1),n,n);

答案 1 :(得分:1)

这是一种矢量化方法:

r = 100;  %// number of rows
c = 100;  %// number of columns
m = 10;   %// number of ones that there should be in each column
H = sparse([], [], [], r, c, c*m);     %// preallocate and initiallize to zero
[~, ind] = sort(rand(r,c));            %// randomly generate...
ind = ind(1:m,:);                      %// ... m row indices per column
H(bsxfun(@plus, ind, (0:c-1)*r)) = 1;  %// fill in ones, using linear indexing
相关问题