Theo
Theo

Reputation: 179

Efficient creation of logical sparse matrix

My goal is to create a rectangular grid and assign a yes/no value to each point. I wans a quite large grid, so I decided to store it as a sparse matrix. My approach considers an N x N grid, with only a ratio r of points to be true (so Nact = r*N^2 points):

N = 200;
r = 0.25;
NAct = r*N^2;
ss = spalloc(ceil(N),ceil(N),ceil(NAct));
for j = 1:N, for i = 1:N, ss(i,j) = rand < r; end; end;
ssL = logical(ss);

However this seems not efficient for large N.

I also tried this:

N = 200;
r = 0.25;
NAct = r*N^2;
iAct = randi(N,1,N);
jAct = randi(N,1,N);
sssL = sparse(iAct,jAct,true,ceil(N),ceil(N),ceil(NAct));
nnz(sssL)

as an alternative, but I have two problems: the true points are N instead of NAct, and there is an error if two pairs of elements of iAct and jAct coincide.

Upvotes: 0

Views: 263

Answers (2)

Theo
Theo

Reputation: 179

I have finally used sprand

N = 200;
r = 0.25;
NAct = r*N^2;
ss = sprand(N,N,r);
ssL = logical(ss);

Upvotes: 2

Adriaan
Adriaan

Reputation: 18207

N = 200;
Grid(N,N) = false; %// preallocate grid
Grid = sparse(Grid); %// add to make sparse
r = 213;
TruePoints = randi(N^2,r,1); %// get random indices of points to be true
Grid(TruePoints) = true;
Grid = logical(Grid); %// switch to logical

Upvotes: 0

Related Questions