Eigen 自定义点类型
时间: 2023-12-21 12:55:11 浏览: 46
Eigen 允许用户自定义点类型,使得用户可以方便地存储和操作自定义的数据类型。自定义点类型需要定义一些必要的成员函数和类型别名,以适配 Eigen 的 API 接口。
首先,定义一个自定义的点类型 `MyPoint`,具有 x, y, z 三个坐标成员:
```c++
class MyPoint {
public:
double x, y, z;
};
```
然后,定义 `MyPoint` 类型的别名 `MyPointType`,以便可以在 Eigen 矩阵中使用:
```c++
typedef MyPoint MyPointType;
```
接下来,需要为 `MyPoint` 类型定义一些必要的成员函数,包括:
- `MyPointType::operator[]`,用于获取点的每个坐标成员;
- `MyPointType::operator[]`,用于获取点的每个坐标成员的常量引用;
- `MyPointType::InnerStrideAtCompileTime`,用于指定点的内部步长,默认为 1。
具体实现如下:
```c++
namespace Eigen {
template<>
struct NumTraits<MyPoint> : NumTraits<double> {
typedef MyPoint Real;
typedef MyPoint NonInteger;
typedef MyPoint Nested;
enum {
IsComplex = 0,
IsInteger = 0,
IsSigned = 1,
RequireInitialization = 1,
ReadCost = 3,
AddCost = 3,
MulCost = 3
};
};
template<>
class Map<MyPoint> {
public:
typedef MyPointType BaseType;
inline Map(BaseType* ptr) : data_(ptr) {}
inline double& operator[](int i) { return data_[i]; }
inline const double& operator[](int i) const { return data_[i]; }
inline int InnerStrideAtCompileTime() const { return 1; }
private:
BaseType* data_;
};
template<>
class Map<const MyPoint> {
public:
typedef const MyPointType BaseType;
inline Map(const BaseType* ptr) : data_(ptr) {}
inline const double& operator[](int i) const { return data_[i]; }
inline int InnerStrideAtCompileTime() const { return 1; }
private:
BaseType* data_;
};
}
```
最后,在使用自定义点类型时,需要使用 `Eigen::Map` 类对存储数据的内存进行映射。例如,创建一个 3x3 的矩阵,存储三个自定义点:
```c++
Eigen::Matrix<MyPoint, 3, 3> matrix;
MyPoint pts[9];
matrix = Eigen::Map<Eigen::Matrix<MyPoint, 3, 3> >(pts);
```
这样,就可以方便地使用自定义点类型进行矩阵计算了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)