patterncppMinor
Matlab any function in C / C++
Viewed 0 times
anyfunctionmatlab
Problem
Due to software constraints, I cannot use the standard libraries,
I need to duplicate the Matlab any function in C / C++ for an array. I currently have written two any functions with different inputs depending on the array size.
I am striving for
math.h, algorithm, templates, inline, or boost. I am also using standard C (ISO C99) such that array is not a reserved keyword like it is in Visual Studio.I need to duplicate the Matlab any function in C / C++ for an array. I currently have written two any functions with different inputs depending on the array size.
- Is it possible to write just one
anyfunction without using templates?
- How can I improve performance?
I am striving for
const correctness, performance/efficiency, and avoiding implicit type casting. bool any(bool* array, const int N){
// mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
bool val;
val = array[0] == true;
int i = 0;
while (val == false && i < N){
val = array[i++] == true;
}
return val;
}
bool any(bool** array, const int nRow, const int nCol){
// mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
bool val;
val = array[0][0] == true;
int i = 0;
while (i < nRow && val == false){
int j = 0;
while (j < nCol && val == false){
val = array[i][j++] == true;
}
i++;
}
return val;
}Solution
I would suggest having the 2D implementation call the 1D implementation, rather than duplicating the "any" logic in both implementations, e.g.
bool any(bool** array, const int nRow, const int nCol){
// mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
bool val = false;
for (int i = 0; i < nRow && val == false; ++i)
{
val = any(array[i], nCol); // call 1D version of any
)
return val;
}Code Snippets
bool any(bool** array, const int nRow, const int nCol){
// mimics the behavior of Matlab's any() function. Returns true if any element of the array is true
bool val = false;
for (int i = 0; i < nRow && val == false; ++i)
{
val = any(array[i], nCol); // call 1D version of any
)
return val;
}Context
StackExchange Code Review Q#5178, answer score: 2
Revisions (0)
No revisions yet.