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

Couple of newbie questions

Tags: None
(comma "," separated)
vak
Registered Member
Posts
23
Karma
0
OS

Couple of newbie questions

Mon Mar 05, 2012 3:01 am
Dear All,


Below is a small function to illustrate my question.

I have a vector whose size will growth from one
iteration to the next, from h=1 to h=h_m.

I couldn't find and equivalent to the .reserve()
function for (non sparse) eigen objects. Is there a way to skip all those resizes()? Does it matter for performances?


//we always have that h<h_m<n//


int h=10,j=0;
MatrixXf xSub(h,p); //a.1
VectorXi Indexn1(n); //a.2
//declare the vector to its final size: //a.3
VectorXi RIndex(h); //a.4
VectorXf dS(n);
RowVectorXf xSub_mean(p);

while(h<h_m){ //b.0
j++; //b.4
h=ceil(j/(2.0*J)*(n-p-1)+p+1); //b.5
Indexn1.setLinSpaced(n,0,n-1); //b.1
random_shuffle(Indexn1.data(),Indexn1.data()+n); //b.2
RIndex.segment(0,h) = Indexn1.segment(0,h); //b.3
xSub.resize(h,NoChange);
//RSubMatrix(x,RIndex) puts in a matrix the entries
//of x with indeces in RIndex.
xSub = RSubMatrix(x,RIndex);
xSub_mean = xSub.colwise().mean();
dS = StatDist(x,xSub,xSub_mean);
std::nth_element(dS.data(),dS.data()+h,dS.data()+n);
std::cout << "Eval: " << dS(h) << endl;
}


Thanks in advance,
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Couple of newbie questions  Topic is solved

Mon Mar 05, 2012 9:50 pm
Eigen::Matrix<> objects are aimed to be as lightweight as possible, so there is no such "reserve" ability. There are many solutions though:

1- if h_m (or n) is not too large and is known at compile time you can statically allocate it and resize it for free:

Matrix<float, Dynamic, 1, 0, n, 1> xSub.

2- You can dynamically allocate n floats and then map it, e.g.:

float* data = new float[n];

loop:
Map<VectorXf> xSub(data, h);


3- You resize xSub once and for all and then use only the h first elements:

VectorXf xSub(n);

and in the loop you use:

xSub.head(n)

4- you can also name the object returned by head():

VectorXf data(n);

loop:
VectorBlock<VectorXf,Dynamic> xSub(data.head(h));


Bookmarks



Who is online

Registered users: Bing [Bot], claydoh, Google [Bot], rblackwell, Yahoo [Bot]