This forum has been archived. All content is frozen. Please use KDE Discuss instead.

matlab diff alternative

Tags: None
(comma "," separated)
grinderfox
Registered Member
Posts
9
Karma
0

matlab diff alternative

Wed Jun 20, 2012 8:17 am
how can one write the code below in more compact and faster way?
Code: Select all
const int sz=10;
VectorXd v = VectorXd::Random(sz);
 VectorXd vdiff(v.size()-1);
 for(int j=0; j<vdiff.size(); ++j)
  { vdiff(j)=v(j+1)-v(j);  }
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: matlab diff alternative  Topic is solved

Wed Jun 20, 2012 8:21 am
int n = v.size();
vdiff = v.head(n-1) - v.tail(n-1);

and for a matrix:
int n = mat.rows(), m=mat.cols();
mdiff = mat.topLeftCorner(n-1,m-1) - mat.bottomRightCorner(n-1,m-1);
grinderfox
Registered Member
Posts
9
Karma
0

Re: matlab diff alternative

Wed Jun 20, 2012 9:06 am
Only small correction:
for vectors one should switch tail and head in order to get the result as described in the first post
vdiff = v.tail(n-1) - v.head(n-1);


Bookmarks



Who is online

Registered users: Baidu [Spider], Bing [Bot], Google [Bot], rblackwell