Equivalent of Matlab find function for C arrays
I need the equivalent of the Matlab find
function (reference) in C for arrays:
ind = find(X) locates all nonzero elements of array X, and returns the linear indices of those elements in vector ind. If X is a row vector, then ind is a row vector; otherwise, ind is a column vector. If X contains no nonzero elements or is an empty array, then ind is an empty array.
A trivial untested example:
#include <stdlib.h>
#include <time.h>
int main()
{
/* Initialize variables */
int x[25];
int y[25];
/* initialize random seed: */
srand ( time(NULL) );
/* Fill arrays with stuff */
for (i=0;i<25;i++)
{
x[i] = rand();
y[i] = rand();
}
/* Find */
ind = find((x-y) > 0); // Need to figure out how to do this
}
}
Now the kicker is I can't use Boost or C++ containers like 开发者_开发技巧vector
due to project constraints.
If you are restricted to "vanilla C" (which seems to be the case, from your question) there's nothing like that built-in, you have to write your own version of such function.
But from what I see from your example you need something different than a find
function, you want to find the elements differing into x
and y
. If you strive for flexibility it could be a good idea to write a generic function that checks the given predicate (passed as a function pointer) on two arrays. On the other hand, since in C we have only function pointers (and not functors) performance may suffer.
This should do something close to what you want - returns number of non-zero elements that it has placed in outArray for you. Not quite the same calling signature, but should do what you want. Untested :)
size_t find(int *inArray, int *outArray, size_t arraySize)
{
size_t numElements = 0;
for(int i=0; i<arraySize; i++)
{
if(inArray[i])
{
outArray[numElements++] = inArray[i];
}
}
return numElements;
}
精彩评论