Generate a random sparse matrix with N nonzero elements

I wrote a function that generates a sparse matrix of size nxd
and places 2 nonzero values ​​in each column.

function [M] = generateSparse(n,d)
    M = sparse(d,n);
    sz = size(M);
    nnzs = 2;
    val = ceil(rand(nnzs,n));
    inds = zeros(nnzs,d);
    for i=1:n
        ind = randperm(d,nnzs);
        inds(:,i) = ind;
    end 
    points = (1:n);
    nnzInds = zeros(nnzs,d);
    for i=1:nnzs
        nnzInd = sub2ind(sz, inds(i,:), points);
        nnzInds(i,:) =  nnzInd;
    end
    M(nnzInds) = val;
end

However, I would like to provide the function with another parameter num-nnz , which will force it to select random num-nnz cells and put 1 there.

I cannot use sprand , since it requires density, and I need the number of nonzero entries to be dependent on the size of the matrix. The density pressure mainly depends on the size of the matrix.

I got a little confused about how to select indexes and populate them ... I did with a loop that was extremely expensive and would appreciate help.

EDIT:
. , .

+4
1

!

num_nnz () 1 , 1 .

, randperm. , numel.

M = sparse(d, n); % create dxn sparse matrix
num_nnz = 10;     % number of non-zero elements
idx = randperm(numel(M), num_nnz); % get unique random indices
M(idx) = 1;       % Assign 1 to those indices
+3

Source: https://habr.com/ru/post/1681802/


All Articles