NOP
NOP

Reputation: 854

Eigen: Efficient equivalent to MATLAB's changem()?

I am needing to perform an operation on an Eigen VectorXi, which is equivalent to MATLAB's changem():

http://www.mathworks.com/help/map/ref/changem.html

At the moment, the way I am doing this is looping over the values in the array and performing the remapping with a switch/case block. I am guessing this is not particularly efficient.

Is there a fast way to do this with Eigen? Speed is critical for my application.

Upvotes: 0

Views: 184

Answers (1)

Malcolm McLean
Malcolm McLean

Reputation: 6404

Switch / case will be particularly slow and inflexible.

changem takes a matrix and two vectors of values, new and old. If an entry is found in the old list, it is replaced by the corresponding entry in the new list. So it's inherently going to be rather slow, you need to pass over the entire matrix, search the old list, and if, and entry is found, replace with the new list. How can you speed it up? First, don't hardcode as a switch / case. A modern compiler will possibly optimise to a loop rather than lots of jumps, but I wouldn't guarantee it. And the approach is inflexible. Secondly, you can sort the "old" vector and use a binary search rather than a linear one. That will only help significantly if the old vector is long. Thirdly, you can take advantage of what you know about the matrix. Are the old values constrained to lie in certain regions? Is there one value which is overwhelmingly likely and can be tested for first? Can you quickly exclude some values as not allowed in the old list (Too big, too small, not integral).

Are the old values integers and can you use indexing? Or generalise that to hashing. That would be even faster than a binary search, though with more overhead for hashing. Can you solve the problem another way and keep an index of matrix xy co-ordinates by value?

There are lots of approaches. But simply implement the Matlab function naively in C as the first step. It might well be fast enough.

Upvotes: 1

Related Questions