7

How do I get an array of nonzero locations (indices) and values of a sparse matrix in Armadillo C++?

So far, I can easily construct a sparse matrix with a set of locations (as a umat object) and values (as a vec object):

// batch insertion of two values at (5, 6) and (9, 9)
umat locations;
locations << 5 << 9 << endr
          << 6 << 9 << endr;

vec values;
values << 1.5 << 3.2 << endr;

sp_mat X(locations, values, 9, 9);

How do I get back the locations? For example, I want to be able to do something like this:

umat nonzero_index = X.locations()

Any ideas?

Bluegreen17
  • 983
  • 1
  • 11
  • 25
  • Your code has a bug: instead of `X(locations, values, 9, 9)`, it has to be `X(locations, values, 10, 10)`. Because C++ starts counting from 0, location (9,9) is referring to the 10-th row and 10-th column. – mtall Mar 11 '15 at 09:01

1 Answers1

16

The associated sparse matrix iterator has .row() and .col() functions:

sp_mat::const_iterator start = X.begin();
sp_mat::const_iterator end   = X.end();

for(sp_mat::const_iterator it = start; it != end; ++it)
  {
  cout << "location: " << it.row() << "," << it.col() << "  ";
  cout << "value: " << (*it) << endl;
  }
mtall
  • 3,574
  • 15
  • 23
  • Is there no direct way to get the same `locations` and `values` arrays that one might use for constructing an `sp_mat`? Is the only way iterating through the elements, as you showed? – Szabolcs Oct 11 '17 at 19:31
  • @Szabolcs - maybe submit a patch to the Armadillo developers? – mtall Oct 12 '17 at 04:06