Swizzle operators for Eigen

#296 Open
Repository
Vertexwahn
Branch
default
Repository
eigen
Branch
default

Bitbucket cannot automatically merge this request.

The commits that make up this pull request have been removed.

Bitbucket cannot automatically merge this request due to conflicts.

Review the conflicts on the Overview tab. You can then either decline the request or merge it manually on your local system using the following commands:

hg update default
hg pull -r default https://bitbucket.org/Vertexwahn/eigen
hg merge 7f60afadd09c
hg commit -m 'Merged in Vertexwahn/eigen (pull request #296)'
Author
  1. Julian Amann
Reviewers
Description

Swizzle operators for Eigen

Please introduce swizzle operators to Eigen such as:

// Examples
Eigen::Vector4d v(1, 2, 3, 4);
v.xy();
v.yx(),
v.xyz();
v.wxzy();
v.xyxy);

Swizzle operators have several advantages:

#include <Eigen/Dense>

// Current state
Eigen::Vector4d point(1, 2, 3, 4);
Eigen::Vector2d v1 = point.block<2, 1>(0, 0); // get x and y coordinate of point in a new vector
Eigen::Vector2d v2 = point.block<2, 1>(2, 0); // get z and w coordinate of point in a new vector

// Improvement
Eigen::Vector2d v3 = point.xy(); // easier to read - shorter to write
Eigen::Vector2d v4 = point.zw(); // less prone to typing errors

std::cout << v1 << std::endl; // output 1, 2
std::cout << v2 << std::endl; // output 3, 4
std::cout << v3 << std::endl; // output 1, 2
std::cout << v4 << std::endl; // output 3, 4

When I tried the first time to get the z and w coordinate of a 4D vector I typed the following code:

Eigen::Vector2d v2 = point.block<2, 1>(0, 2); // get z and w coordinate of point in a new vector

The above code is incorrect, but that is hard to see. Writing .zw() would fix those issues.

In our codebase, we use 76 times the .block member method. I am quite sure that sometimes the wrong elements are accessed. We moved from a library that supported swizzle operators to Eigen and replaced all occurrences of swizzles with the .block member function - but we are not happy with that situation.

If you try to access an invalid member as shown in the example bellow you get an error (OUT_OF_RANGE_ACCESS) during compiling.

Eigen::Vector2d v(1, 2);
v.zz();

I recommend accepting my pull request to improve this situation.

Commit Logs

  • Added read-only access swizzle operators to DenseCoeffsBase class.

  • Added copyright notes.

Comments (4)

  1. Christoph Hertzberg

    IMO, this looks like a lot of boiler-plate code. Also, I'd expect (at least the swizzles without duplicates) to be writable. Using the devel-branch and C++11 you can already write:

    Eigen::Vector2d v1 = point({0,1}); // [point.x(), point.y()]
    point({2,3}).setZero(); // point.z()=point.w()=0;
    
  2. Julian Amann author

    What do you mean by duplicates?

    Eigen::Vector4d point(1, 2, 3, 4);
    Eigen::Vector2d v1 = point.xw(); // v1 = (1,4)
    Eigen::Vector2d v2 = point.wx(); // v2 = (4,1)