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

Eigen VectorXf: Resetting without changing the size

Tags: None
(comma "," separated)
pamparana
Registered Member
Posts
18
Karma
0
I have a question about the Eigen VectorXf. Currently, I am doing the following in a loop as follows:

Code: Select all
for (int i = 0; i < num_iterations; ++i) {
    Eigen::VectorXf temp (some_size);
    temp << some_computed_value;
    temp << some_other_computed_value;
    temp << they_another_value;
}


Since the vector does not change size, it would be more desirable to do the following:

Code: Select all
Eigen::VectorXf temp (some_size);
for (int i = 0; i < num_iterations; ++i) {
   // Call some function here that will keep the size of the vector but
   // insert these values from the beginning of the array
    temp << some_computed_value_array;
    temp << some_other_computed_value_array;
    temp << yet_another_value_array;
}


So what I would like to do is to overwrite the array at each loop iteration. My understanding is that the << operator does a push_back which would resize the array if I declare it as I currently do.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
"<<" does not change the size of the destination, however, it is not as efficient as operator = when assigning a matrix/vector to another matrix/vector. The recommended way in your case is thus:
Code: Select all
Eigen::VectorXf temp (some_size);
for (int i = 0; i < num_iterations; ++i) {
   // Call some function here that will keep the size of the vector but
   // insert these values from the beginning of the array
    temp = some_computed_value_array;
    temp = some_other_computed_value_array;
    temp = yet_another_value_array;
}


No resizing, no memory reallocation, unless the size of "some_whatever_array" is not some_size.
pamparana
Registered Member
Posts
18
Karma
0
Sorry I made a small mistake in my original post. The use I was intending was something like:

Code: Select all
Eigen::VectorXf temp (some_size);
for (int i = 0; i < num_iterations; ++i) {
   // Call some function here that will keep the size of the vector but
   // insert these values from the beginning of the array
    temp  << array_block_1, array_block_2, array_block_3;

    // further computations...
}


Here the sum of the size of the three array blocks equal to some_size. Is it safe to do it like this in a loop. The array size should not change but it should get refreshed with the new values at every iteration.

Sorry for causing the confusion due to my stupidity.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS
Actually, to make << works the sum of sizes *must* equals to some_size. Otherwise, you will get an assertion error. So yes, your use case is perfectly fine, and no memory re-allocation occur.


Bookmarks



Who is online

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