fn_find.hpp

Go to the documentation of this file.
00001 // Copyright (C) 2010 NICTA and the authors listed below
00002 // http://nicta.com.au
00003 // 
00004 // Authors:
00005 // - Dimitrios Bouzas (dimitris dot mpouzas at gmail dot com)
00006 // - Conrad Sanderson (conradsand at ieee dot org)
00007 // 
00008 // This file is part of the Armadillo C++ library.
00009 // It is provided without any warranty of fitness
00010 // for any purpose. You can redistribute this file
00011 // and/or modify it under the terms of the GNU
00012 // Lesser General Public License (LGPL) as published
00013 // by the Free Software Foundation, either version 3
00014 // of the License or (at your option) any later version.
00015 // (see http://www.opensource.org/licenses for more info)
00016 
00017 
00018 //! \addtogroup fn_find
00019 //! @{
00020 
00021 
00022 
00023 template<typename eT>
00024 arma_hot
00025 inline
00026 u32
00027 find_helper(u32* out_mem, const eT* in_mem, const u32 n_elem)
00028   {
00029   arma_extra_debug_sigprint();
00030   
00031   u32 n_nz = 0;
00032   
00033   for(u32 i=0; i<n_elem; ++i)
00034     {
00035     if(in_mem[i] != eT(0))
00036       {
00037       out_mem[n_nz] = i;
00038       ++n_nz;
00039       }
00040     }
00041    
00042   return n_nz;
00043   }
00044 
00045 
00046 // TODO:
00047 // once the relational operators are changed into delayed operations,
00048 // find() will need special handling of relational operators to gain speed
00049 template<typename T1>
00050 inline
00051 Mat<u32>
00052 find(const Base<typename T1::elem_type,T1>& X, const u32 k = 0, const char* direction = "first")
00053   {
00054   arma_extra_debug_sigprint();
00055   
00056   typedef typename T1::elem_type eT;
00057   
00058   const unwrap<T1>   tmp(X.get_ref());
00059   const Mat<eT>& A = tmp.M;
00060   
00061   const u32 n_elem = A.n_elem;
00062   
00063   Mat<u32> indices(n_elem, 1);
00064   
00065   const u32 n_nz = find_helper(indices.memptr(), A.memptr(), n_elem);
00066   
00067   const char sig = direction[0];
00068   
00069   // return the indices of all n_nz elements, otherwise return an empty matrix
00070   if(n_nz > 0)
00071     {
00072     if(sig == 'f' || sig == 'F')   // "first"
00073       {
00074       return ( (k > 0 && k <= n_nz) ? indices.rows(0,      k-1   ) : indices.rows(0, n_nz-1) );
00075       }
00076     else
00077     if(sig == 'l' || sig == 'L')   // "last"
00078       {
00079       return ( (k > 0 && k <= n_nz) ? indices.rows(n_nz-k, n_nz-1) : indices.rows(0, n_nz-1) );
00080       }
00081     else
00082       {
00083       arma_stop("find(): 3rd input argument must be \"first\" or \"last\"");
00084       
00085       return Mat<u32>();
00086       }
00087     }
00088   else
00089     {
00090     return Mat<u32>();
00091     }
00092   }
00093 
00094 
00095 
00096 //! @}