0
votes

Is there is a simple way to ensure that the randomly created sparse matrix have non-zero elements in all rows and columns?

I have tried sprand to create m*n matrix

Matrix=sprand(m,n,0.3)

But there is sometimes that a non-zero row or column is found.

I have also tried to create a matrix by creating a sparse vector as row and add a row after row to the matrix.

Edit: I am looking for a small size matrix 5*5 matrix for rxample

1
So you want all rows and all columns to have at least one non-zero element? Does the density have to be exactly 0.3 or is it enough to have something close? I.e. is it OK to insert some random numbers in locations that would create an OK matrix? - Stewie Griffin
Approximately, how big are your matrices? - Stewie Griffin
Thanks for your comments, I need the density to be less than 0.5 and the non-zero elements locations to be random. Th size of the matrix is small matrices around 5*5 - OBtli

1 Answers

2
votes

Create the indices manually:

m = 10;
n = 8;
p = 0.3;

r = repmat(randperm(m), 1, n);
c = repmat(randperm(n), 1, m);
row_idx = r(1:ceil(p*m*n));
col_idx = c(1:ceil(p*m*n));
ran_num = rand(1, ceil(p*m*n));

s = sparse(row_idx, col_idx, ran_num, m, n);
full(s)

    0.1842         0         0         0    0.0133         0    0.0620         0
         0         0         0         0    0.2999         0    0.1967         0
         0         0         0    0.1341         0         0         0    0.0934
         0         0    0.4561         0         0         0         0    0.8949
    0.1017    0.0715         0         0         0         0         0         0
    0.0538    0.7363         0         0    0.3321         0         0         0
         0         0    0.5619    0.2973         0    0.4417         0         0
         0         0         0    0.8972         0    0.5972         0         0
         0         0    0.2425         0         0    0.9954         0    0.7455
         0    0.3074         0         0         0         0    0.2126         0

Test of sparsity:

nnz(s)/numel(s)    
ans =    
    0.3000

Below is a smaller example. It's impossible to have a density lower than 0.5, and dimensions 5x5, and still have a non-zero element in all rows and columns.

m = 5;
n = 5;
p = 0.5;

r = repmat(randperm(m), 1, n);
c = repmat(randperm(n), 1, m);
row_idx = r(1:ceil(p*m*n));
col_idx = c(1:ceil(p*m*n));
ran_num = rand(1, ceil(p*m*n));

s = sparse(row_idx, col_idx, ran_num, m, n);
full(s)

ans =

    1.8078         0         0         0         0
         0         0         0    0.7891         0
         0    1.5096         0         0         0
         0         0         0         0    1.0909
         0         0    1.1130         0         0