Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nonzero elements of sparse Matrix

let's say I have a big Matrix X with a lot of zeros, so of course I make it sparse in order to save on memory and CPU. After that I do some stuff and at some point I want to have the nonzero elements. My code looks something like this:

 ind = M ~= 0; % Whereby M is the sparse Matrix

This looks however rather silly to me since the structure of the sparse Matrix should allow the direct extraction of the information.

To clarify: I do not look for a solution that works, but rather would like to avoid doing the same thing twice. A sparse Matrix should perdefinition already know it's nonzero values, so there should be no need to search for it.

yours magu_

like image 659
magu_ Avatar asked Jan 29 '26 20:01

magu_


2 Answers

The direct way to retrieve nonzero elements from a sparse matrix, is to call nonzeros().

The direct way is obviously the fastest method, however I performed some tests against logical indexing on the sparse and its full() counterparty, and the indexing on the former is faster (results depend on the sparsity pattern and dimension of the matrix).

The sum of times over 100 iterations is:

nonzeros:   0.02657 seconds
sparse idx: 0.52946 seconds
full idx:   2.27051 seconds

The testing suite:

N = 100;
t = zeros(N,3);
for ii = 1:N
    s = sprand(10000,1000,0.01);
    r = full(s);

    % Direct call nonzeros
    tic
    nonzeros(s);
    t(ii,1) = toc;

    % Indexing sparse
    tic
    full(s(s ~= 0));
    t(ii,2) = toc;

    % Indexing full
    tic
    r(r~=0);
    t(ii,3) = toc;
end

sum(t)
like image 91
Oleg Avatar answered Jan 31 '26 09:01

Oleg


I'm not 100% sure what you're after but maybe [r c] = find(M) suits you better?

You can get to the values of M by going M(r,c) but the best method will surely be dictated by what you intend to do with the data next.

like image 28
Dan Avatar answered Jan 31 '26 09:01

Dan