指向切成薄片的特征矩阵
我有一个函数,该函数将指针指向特征矩阵。我需要将此矩阵切成几片,然后将矩阵的一部分传递给该函数。我想避免复制数据,因此我想用指针将其传递。
我切一个矩阵,例如:
MatrixXd A;
// some operations with the matrix
// now I want something like this:
MatrixXd *B = &A(seq(2, 4), all);
最后一行是无效的。我如何获取指向矩阵的指针,以便仍然可以将其视为特征矩阵?有解决方法吗?同样,我想避免创建新矩阵,就像我的真实程序中一样大。
I have a function which takes a pointer to an Eigen matrix. I need to slice this matrix to several pieces and pass a portion of the matrix to the function. I want to avoid copying data, so I want to pass it with a pointer.
I slice a matrix, for example like this:
MatrixXd A;
// some operations with the matrix
// now I want something like this:
MatrixXd *B = &A(seq(2, 4), all);
The last line is invalid. How can I get a pointer to a piece of matrix so that it can still be treated as an Eigen matrix? Are there any workarounds? Again, I'd like to avoid creating new matrices as in my real program they are quite big.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是
eigen :: ref
是用来的。 “如何写通用但非塑造功能?请参阅 这样:
存储块引用
eigen不带有非常适合保留矩阵的“借用”块表达式的类型。对于这种情况,我不推荐
ref
,因为它太容易了,无法指出临时分配,这很容易导致悬挂的指针。最终,存储借来的观点是从根本上不安全的操作。但是,如果您绝对必须这样做,我将使用
eigen :: Map
。至少这清楚地表明,您不拥有所引用的内存。类似的事情:一个稍微更安全的选项是将
shared_ptr
保留到矩阵中,并存储信息单独使用的切片。也许这样:这样,即使在调整了矩阵和悬空指针大小后,参考文献也将保持有效。只有缩水仍然是一个威胁,但假设您与他们进行了编译,那会被断言所抓住。
That's what
Eigen::Ref
was built for. See the section "How to write generic, but non-templated function?"Something like this:
Storing block references
Eigen doesn't come with a type that is well-suited to keep a "borrowed" block expression of a matrix. I wouldn't recommend
Ref
for this case because it is far too easy to make it point at temporary allocations which can easily lead to dangling pointers.Ultimately, storing borrowed views is a fundamentally unsafe operation. But if you absolutely have to do it, I would use an
Eigen::Map
. At least that makes it clear you aren't owning the memory to which you refer. Something like this:A slightly safer option is to keep a
shared_ptr
to the matrix and store the information what slice you use separately. Maybe like this:That way, the reference will remain valid even after resizing the matrix and dangling pointers are avoided. Only shrinking remains a threat but that is caught by assertions, assuming you compile with them.