Search code examples
matlabsparse-matrix

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_


Solution

  • 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)