Skip to content

Instantly share code, notes, and snippets.

@ityonemo
Created January 13, 2013 00:35
Show Gist options
  • Save ityonemo/4521328 to your computer and use it in GitHub Desktop.
Save ityonemo/4521328 to your computer and use it in GitHub Desktop.
generates a cell list of variational parameters for a sparse array. Useful for doing gradient descent on said array.
#include <octave/oct.h>
#include <octave/Cell.h>
// SPECIAL FUNCTION THAT CONVERTS A SPARSE MATRIX
// TO A MATRIX THAT LISTS (ROW COLUMN) OF THE FILLED VALUES
DEFUN_DLD (cmtxvars, args, nargout, "creates a cell matrix of variations on a sparse 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 ();
//pull the amount we're going to do variation by from the argument.
double delta = (nargin > 1) ? args(1).float_value() : 0.01;
//count how many elements we have, this should also be
//the length of ri array
int count = sm.nelem();
//save the original dimensions vector.
dim_vector smsize(sm.dim1(), sm.dim2());
//cursor will be used to iterate over ci array.
int cursor = 0;
//allocate a new cell array to store our variational matrices.
dim_vector cmsize(count);
Cell c(cmsize);
//iterating over the length of the sparse matrix:
for (int index = 0; index < count; index++)
{
//create a new sparse matrix.
SparseMatrix tm(sm);
//add the variational parameter into the matrix.
tm.data()[index] += delta;
//store it into the cell array
c(index) = tm;
}
//return the cell array.
return octave_value (c);
}
return octave_value_list ();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment