help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Sparse Matrix non zero elements in each row


From: Joao F. D. Rodrigues
Subject: Re: Sparse Matrix non zero elements in each row
Date: Fri, 07 Aug 2015 11:12:44 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.7.0



On 06-08-15 14:45, Shamika Mohanan wrote:
I'm creating a sparse matrix using Octave in c++ code. The code is-

octave_value_list out = feval (pstData[0], in, 1);
if(out(0).is_sparse_type())
{
  SparseMatrix sparse_matrix=out(0).sparse_matrix_value ();
int iNbItem= sparse_matrix.nnz(); //Get number of non zero elements in sparse matrix
}

How do I get the number of non zero elements in each row and the column indices of the non zero elements?

Shamika

A basic (and probably inefficient) alternative to the suggestion of Kai is to use:

[rowind, colind, val] = find(sparse_matrix);

then row indices should be sorted. If not:

[rowind, isort] = sort(rowind);
colind = colind(isort);

colind is now the sorted list of column indices. You still need to find out which row they belong to.

You can use a row sum to find out the total number of elements in each row

nnzrow = full(sum((spare_matrix)!=0),2));

In principle there might be empty rows, so the optimal way to proceed depends strongly on how you want to access this information later on. One possible way is to have two vectors, whose length is the number of non-empty rows in the original matrix, one with the index of the row:

posrow = nonzeros(nnzrow);

and the other with the final element in colind belonging to row i, assuming the first element is poscol(i-1)+1. Again, there are different ways of building poscol, depending on its size. The more obvious option is:

poscol = find(nnzrow);
for i  = 2 : length (poscol)
    poscol(i) = poscol(i-1) + poscol(i);
endfor

I am sure there are simple ways to circumvent the loop, but right now I can only think of repmat, triu and sum, which would require creating potentially large dense matrix objects.


















reply via email to

[Prev in Thread] Current Thread [Next in Thread]