user3371282
user3371282

Reputation: 103

Creating a sparse matrix in Matlab with a specified number of independent Bernoulli +-1 nonzero entries

How in Matlab we can form a matrix X, 1000 by 1000, which is sparse with, say,

5% of independent Bernoulli +-1 nonzero entries?

I.e. such a matrix would have rho = ||X||_0/10^6 = 0.05.

Upvotes: 0

Views: 139

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112689

If you need to build the matrix as sparse (in Matlab's sense):

M = 1000; %// number of rows
N = 1000; %// number of columns
perc = 5/100; %// percentage (fraction) of +/-1 entries

n = round(M*N*perc); %// compute number of nonzero entries
nz = 2*(rand(1,n)<.5)-1; %// generate nonzero entries: +/-1 with .5 probability
ind = randsample(M*N,n); %// choose linear indices of nonzero entries
X = sparse(ind, 1 ,nz , M*N, 1, n); %// build matrix as linearized
X = reshape(X,M,N); %// put into shape

Upvotes: 1

Yvon
Yvon

Reputation: 2983

Randomly choose 5% of elements

n = numel(X);
ind = randi(n, round(.05*n), 1);

Assign these elements with random variable

X(ind) = binornd(1, .5, length(ind), 1) *2-1;

Check binornd's documentation for more details.

To avoid duplicate randi numbers, you can use randsample from the Statistics Toolbox, or something like randperm as mentioned in this post, or something like


EDIT

ind = [];
t0 = round(.05*n);
t1 = length(ind);
while t1 < t0
    ind(end+1:t0) = randi(n, t0-t1, 1);
    ind = unique(ind);
    t1 = length(ind);
end

Upvotes: 1

Related Questions