MATLAB - Create psudorandom sparse matrix

你。 提交于 2021-01-27 10:52:04

问题


Is there an easy way of making a 'random' sparse matrix with a specific number of nonzero entries?

Here is my attempt:

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

But the matrix H doesn't have exactly m nonzeros in each column. For example if I use this to make a 100 x 100 matrix with 10 nonzeros in each column only 10 columns have exactly 10 1's in them.

I'm sure there's an easy way to do this but I can't see it.


回答1:


This will generate a 100-by-100 matrix with exactly ten 1s per column:

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);



回答2:


Here's a vectorized approach:

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


来源:https://stackoverflow.com/questions/28486650/matlab-create-psudorandom-sparse-matrix

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!