vnl_crs_index.cxx
Go to the documentation of this file.
1 // This is core/vnl/vnl_crs_index.cxx
2 //:
3 // \file
4 // \author Matt Leotta (Brown)
5 // \date April 13, 2005
6 
7 #include "vnl_crs_index.h"
8 
9 //: Constructor - from a binary mask
10 vnl_crs_index::vnl_crs_index(const std::vector<std::vector<bool> >& mask)
11  : num_cols_(mask[0].size()), col_idx_(), row_ptr_(mask.size()+1,0)
12 {
13  int k=0;
14  for (unsigned int i=0; i<mask.size(); ++i){
15  const std::vector<bool>& col = mask[i];
16  row_ptr_[i] = k;
17  for (unsigned int j=0; j<num_cols_; ++j){
18  if (col[j]){
19  col_idx_.push_back(j);
20  ++k;
21  }
22  }
23  }
24  row_ptr_[mask.size()] = k;
25 }
26 
27 
28 //: return the index at location (i,j)
29 // returns -1 if the entry is 0
30 int
31 vnl_crs_index::operator() (int i, int j) const
32 {
33  int low = row_ptr_[i];
34  int high = row_ptr_[i+1]-1;
35 
36  // binary search for finding the element at column j
37  while (low<=high){
38  if (j<col_idx_[low] || j>col_idx_[high])
39  return -1; // element is zero (no index)
40 
41  int mid = (low+high)>>1; //(low+high)/2;
42  if (j<(int)col_idx_[mid])
43  high = mid-1;
44  else if (j>(int)col_idx_[mid])
45  low=mid+1;
46  else
47  return mid;
48  }
49 
50  return -1; // element is zero (no index)
51 }
52 
53 
54 //: returns row \p i as a vector of index-column pairs
57 {
58  sparse_vector row;
59  for (int j=row_ptr_[i]; j<row_ptr_[i+1]; ++j){
60  row.push_back(idx_pair(j,col_idx_[j]));
61  }
62  return row;
63 }
64 
65 
66 //: returns column \p j as a vector of index-row pairs
67 // \note because of CRS this method is a bit less efficient than sparse_row
70 {
71  sparse_vector col;
72  for (int i=0; i<num_rows(); ++i){
73  int idx = (*this)(i,j);
74  if (idx >= 0)
75  col.push_back(idx_pair(idx,i));
76  }
77 
78  return col;
79 }
int operator()(int i, int j) const
return the index at location (i,j).
Compressed Row Storage (CRS) indexing.
unsigned int num_cols_
The number of columns in the matrix.
Definition: vnl_crs_index.h:63
int num_rows() const
number of rows in the sparse matrix.
Definition: vnl_crs_index.h:42
sparse_vector sparse_row(int i) const
returns row i as a vector of index-column pairs.
sparse_vector sparse_col(int j) const
returns column j as a vector of index-row pairs.
vnl_crs_index()
Constructor - default.
Definition: vnl_crs_index.h:33
std::pair< int, int > idx_pair
Definition: vnl_crs_index.h:29
std::vector< idx_pair > sparse_vector
Definition: vnl_crs_index.h:30
std::vector< int > row_ptr_
The index of the first non-zero element in each row.
Definition: vnl_crs_index.h:67
std::vector< int > col_idx_
The column for each non-zero element.
Definition: vnl_crs_index.h:65