patterncppMinor
MATLAB and Armadillo, hints on translating
Viewed 0 times
translatingmatlabhintsandarmadillo
Problem
i'm rewriting some Matlab code to c++ using armadillo, a libs for linear algebra. really good libs, IMHO. but i had to translate some matlab construct because armadillo isn't matlab.
i want to share my little snippet because i think there should be a better way (in terms of speed, mainly) to solve thoose little problems. i hope someone here could help me to improve my code!
-
-
-
-
i want to share my little snippet because i think there should be a better way (in terms of speed, mainly) to solve thoose little problems. i hope someone here could help me to improve my code!
static mat log(mat A) {
/*
* log function operates element-wise on matrix A
* MATLAB code> log(A)
*/
mat X(A);
mat::iterator a = X.begin();
mat::iterator b = X.end();
for(mat::iterator i=a; i!=b; ++i) {
(*i) = log(*i);
}
return X;
}-
static mat vectorize(mat A) {
/*
* vectorise a matrix (ie. concatenate all the columns or rows)
* MATLAB code> A(:)
*/
mat B = mat(A);
B.reshape(B.n_rows*B.n_cols, 1);
return B;
}-
static bool any(mat X, double n) {
/*
* check if there are some n in X
* MATLAB code> any(X==n)
* TODO: i'm not sure of description but it works for me
*/
uvec _s = find(, n);
if ( _s.is_empty() )
return true;
else
return false;
}-
static double sum(mat X) {
/*
* sum a matrix
* MATLAB code> sum(X)
*/
return sum(sum(X))
}-
static field, mayebe a template should be used to generalize..
* MATLAB code> num2cell(X)
*/
field data1(X.n_rows,1);
for (uint r = 0; r < X.n_rows; ++r) {
data1(r,0) = X.row(r);
}
return data1;
}Solution
-
You're doing a copy in most of those snippets: if it was possible to do without a copy, it could be faster. Libraries such as Boost often offer two versions of a specific function: one which copies and another one which modifies in place.
-
-
This code:
can be written as:
You're doing a copy in most of those snippets: if it was possible to do without a copy, it could be faster. Libraries such as Boost often offer two versions of a specific function: one which copies and another one which modifies in place.
-
i is enough, you don't need (i):*i = log(*i);-
This code:
if ( _s.is_empty() )
return true;
else
return false;can be written as:
return _s.is_empty();Code Snippets
*i = log(*i);if ( _s.is_empty() )
return true;
else
return false;return _s.is_empty();Context
StackExchange Code Review Q#8938, answer score: 7
Revisions (0)
No revisions yet.