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:
. , .