comparison liboctave/boolSparse.cc @ 10983:4b51c0a20a98

optimize sum of sparse logical matrices
author Jaroslav Hajek <highegg@gmail.com>
date Wed, 15 Sep 2010 22:31:12 +0200
parents 80653e42a551
children d81b79c1bd5d
comparison
equal deleted inserted replaced
10982:1ec2f19857fa 10983:4b51c0a20a98
33 #include "quit.h" 33 #include "quit.h"
34 #include "lo-ieee.h" 34 #include "lo-ieee.h"
35 #include "lo-mappers.h" 35 #include "lo-mappers.h"
36 36
37 #include "boolSparse.h" 37 #include "boolSparse.h"
38 #include "dSparse.h"
38 #include "oct-mem.h" 39 #include "oct-mem.h"
39 #include "oct-locbuf.h" 40 #include "oct-locbuf.h"
40 41
41 // SparseBoolMatrix class. 42 // SparseBoolMatrix class.
42 43
167 tmp.xelem(ridx(i)) = true; 168 tmp.xelem(ridx(i)) = true;
168 retval = tmp; 169 retval = tmp;
169 } 170 }
170 else 171 else
171 { 172 {
172 OCTAVE_LOCAL_BUFFER (octave_idx_type, tmpridx, nz); 173 Array<octave_idx_type> tmp (nz, 1);
173 copy_or_memcpy (nz, ridx (), tmpridx); 174 copy_or_memcpy (nz, ridx (), tmp.fortran_vec ());
174 std::sort (tmpridx, tmpridx+nz); 175 retval = Sparse<bool> (Array<bool> (1, 1, true),
175 octave_idx_type new_nz = std::unique (tmpridx, tmpridx + nz) - tmpridx; 176 idx_vector (tmp), idx_vector (0), nr, 1,
176 retval = Sparse<bool> (nr, 1, new_nz); 177 false);
177 copy_or_memcpy (new_nz, tmpridx, retval.ridx ()); 178 }
178 fill_or_memset (new_nz, true, retval.data ()); 179 }
180
181 return retval;
182 }
183
184 SparseMatrix
185 SparseBoolMatrix::sum (int dim) const
186 {
187 Sparse<double> retval;
188 octave_idx_type nr = rows (), nc = cols (), nz = nnz ();
189 if (dim == -1)
190 dim = (nr == 1 && nc != 1) ? 1 : 0;
191
192 if (dim == 0)
193 {
194 // Result is a row vector.
195 retval = Sparse<double> (1, nc);
196 for(octave_idx_type i = 0; i < nc; i++)
197 retval.xcidx(i+1) = retval.xcidx(i) + (cidx(i+1) > cidx(i));
198 octave_idx_type new_nz = retval.xcidx(nc);
199 retval.change_capacity (new_nz);
200 fill_or_memset (new_nz, static_cast<octave_idx_type> (0), retval.ridx ());
201 for(octave_idx_type i = 0, k = 0; i < nc; i++)
202 {
203 octave_idx_type c = cidx(i+1) - cidx(i);
204 if (c > 0)
205 retval.xdata(k++) = c;
206 }
207 }
208 else if (dim == 1)
209 {
210 // Result is a column vector.
211 if (nz > nr)
212 {
213 // We can use O(nr) memory.
214 Array<double> tmp (nr, 1, 0);
215 for (octave_idx_type i = 0; i < nz; i++)
216 tmp.xelem(ridx(i)) += 1.0;
217 retval = tmp;
218 }
219 else
220 {
221 Array<octave_idx_type> tmp (nz, 1);
222 copy_or_memcpy (nz, ridx (), tmp.fortran_vec ());
223 retval = Sparse<double> (Array<double> (1, 1, 1.0),
224 idx_vector (tmp), idx_vector (0), nr, 1);
179 } 225 }
180 } 226 }
181 227
182 return retval; 228 return retval;
183 } 229 }