Skip to content

Instantly share code, notes, and snippets.

@ityonemo
Created January 8, 2013 07:02
Show Gist options
  • Save ityonemo/4481883 to your computer and use it in GitHub Desktop.
Save ityonemo/4481883 to your computer and use it in GitHub Desktop.
converts a sparse matrix to a list of (row, column) vectors indicating which positions are occupado.
#include <octave/oct.h>
// SPECIAL FUNCTION THAT CONVERTS A SPARSE MATRIX
// TO A MATRIX THAT LISTS (ROW COLUMN) OF THE FILLED VALUES
DEFUN_DLD (torcmtx, args, nargout, "extracts edges of a sparse matrix to a list matrix")
{
int nargin = args.length();
if (nargin != 1)
print_usage (); //make sure we actually sent one value in.
else
{
//pull the sparse matrix from the argument.
SparseMatrix sm = args(0).sparse_matrix_value ();
//temporarily cache the ridx and cidx arrays.
int* ri = sm.ridx();
int* ci = sm.cidx();
//count how many elements we have, this should also be
//the length of ri array
int count = sm.nelem();
//cursor will be used to iterate over ci array.
int cursor = 0;
//allocate a new matrix to store our answer.
Matrix res(count,2);
//iterating over the results:
for (int index = 0; index < count; index++)
{
//the ri array has the row, just put that in the result matrix.
//remember that internally octave indexes the array using 0-indexing
//but octave wants 1s-indexing.
res(index, 0) = ri[index] + 1;
//find the appropriate row in the ci array
while (ci[cursor] <= index)
cursor++;
//since the cursor *passed* the corresponding index that says
//what the column is, no need to subtract one to get 1s-indexing.
res(index, 1) = cursor;
}
//return it.
return octave_value (res);
}
return octave_value_list ();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment