Mercurial > hg > octave-lyh
diff liboctave/sparse-util.cc @ 9469:c6edba80dfae
sanity checks for loading sparse matrices
author | John W. Eaton <jwe@octave.org> |
---|---|
date | Wed, 29 Jul 2009 12:15:27 -0400 |
parents | eb63fbe60fab |
children | 4c0cdbe0acca |
line wrap: on
line diff
--- a/liboctave/sparse-util.cc +++ b/liboctave/sparse-util.cc @@ -1,6 +1,6 @@ /* -Copyright (C) 2005, 2007, 2008 David Bateman +Copyright (C) 2005, 2007, 2008, 2009 David Bateman Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005 Andy Adler This file is part of Octave. @@ -58,6 +58,66 @@ } +bool +sparse_indices_ok (octave_idx_type *r, octave_idx_type *c, + octave_idx_type nrows, octave_idx_type ncols, + octave_idx_type nnz) +{ + if (nnz > 0) + { + if (c[0] != 0) + { + (*current_liboctave_error_handler) + ("invalid sparse matrix: cidx[0] must be zero"); + return false; + } + + octave_idx_type jold = 0; + + for (octave_idx_type j = 1; j < ncols+1; j++) + { + if (c[j] < c[j-1]) + { + (*current_liboctave_error_handler) + ("invalid sparse matrix: cidx elements must appear in ascending order"); + return false; + } + + if (c[j] > nnz) + { + (*current_liboctave_error_handler) + ("invalid sparse matrix: cidx[%d] = %d exceeds number of nonzero elements", j, c[j]+1); + return false; + } + + if (c[j] != jold) + { + for (octave_idx_type i = jold+1; i < c[j]; i++) + { + if (r[i] < r[i-1]) + { + (*current_liboctave_error_handler) + ("invalid sparse matrix: ridx elements must appear in ascending order for each column"); + return false; + } + + if (r[i] >= nrows) + { + (*current_liboctave_error_handler) + ("invalid sparse matrix: ridx[%d] = %d out of range", + i, r[i]+1); + return false; + } + } + + jold = c[j]; + } + } + } + + return true; +} + /* ;;; Local Variables: *** ;;; mode: C++ ***