Reputation: 289
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.
Upvotes: 3
Views: 108
Reputation: 112659
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
Upvotes: 2
Reputation: 6084
This will generate a 100-by-100
matrix with exactly ten 1
s 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);
Upvotes: 3