Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find first ZERO element of a sparse matrix

When using sparse matrices, it's easy to find non-zero entries quickly (as these are the only elements stored). However, what's the best way to find the first ZERO entry? Using approaches like find(X==0,1) or find(~X,1) tend to be slow as these require the negation of the whole matrix. It doesn't feel like that should be necessary -- is there a better way?


For instance, naively iterating over the array seems to be slightly faster than using find(X==0,1):

% Create a sparse array [10% filled]
x = sparse(5000,1);
x(randsample(5000,500)) = 1;
nRuns = 1e5; 
% Find the first element, a million times
idx = zeros(nRuns,1);
tic
for n=1:nRuns
    idx(n) = find(x==0,1);
end
toc


%%
% Create a sparse array [10% filled]
x = sparse(5000,1);
x(randsample(5000,500)) = 1;
nRuns = 1e5; 
% Find the first element, a million times
idx = zeros(nRuns,1);
tic
for n=1:nRuns
    for kk = 1:numel(x)
        [ii,jj] = ind2sub(size(x), kk);
        if x(ii,jj)==0; idx(n) = ii + (jj-1)*n; break; end
    end
end
toc

But what is the best way to do this?

like image 747
magnesium Avatar asked Dec 08 '25 16:12

magnesium


1 Answers

For positive arrays min is probably the fastest solution:

x = sparse(5000, 1);
x(randsample(5000, 500)) = 1; 
[~, idx] = min(x);

ismember can also be used:

[~, ind] = ismember(0, x);
like image 64
rahnema1 Avatar answered Dec 11 '25 10:12

rahnema1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!