user78655
user78655

Reputation: 289

MATLAB - Create psudorandom sparse matrix

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

Answers (2)

Luis Mendo
Luis Mendo

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

knedlsepp
knedlsepp

Reputation: 6084

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

Upvotes: 3

Related Questions