![]() |
Blitz Support : |
From: Jonathan Stickel (jjstickel_at_[hidden])
Date: 2005-06-01 11:05:16
Shubhankar Ray wrote:
> Hello,
>
> I recently started using blitz after coming to know of its Matlab
> like capabilities. I want to know if there is an analogue of the
> Matlab find(). Example, X=[0 1 0 1]; find(X==1) returns [2 4].
>
> In blitz I see that where() can be used to work on specific indices
> satisfying some expression, but is there a quick way to return just
> the indices as an Array<> or vector<>.
>
> thanks
> Shubhankar Ray
>
>
I wrote my own functions to do this. They may not be fast, but they
work (see below). If there is interest, I could submit them to be part
of Blitz.
Jonathan
//Returns the indexes of the nonzero values of a vector. Could expand
//to do multidimensional arrays by vectorizing the array (will wait for
//a need).
void find(Array<int,1> & indexes, const Array<bool,1> & boolVec)
{
int n = boolVec.size();
indexes.resize(n);
int j=0;
for (int i=0; i<n; ++i){
if (boolVec(i)){
indexes(j)=i;
++j;
}
}
if (j)
indexes.resizeAndPreserve(j);
else
indexes.free();
}
//Returns the (i,j) pair of indexes of the nonzero values of a matrix.
//May be slow, but fine for now.
void find(Array<int,2> & indexPairs, const Array<bool,2> & boolMat)
{
int m = boolMat.rows(), n = boolMat.columns();
indexPairs.resize(m*n,2);
int k=0;
for (int i=0; i<m; ++i){
for (int j=0; j<n; ++j){
if (boolMat(i,j)){
indexPairs(k,rAll) = i,j;
++k;
}
}
}
if (k)
indexPairs.resizeAndPreserve(k,2);
else
indexPairs.free();
}