DenseBase,自动和二进制操作表示数组具有不同的形状 [英] DenseBase, auto, and binary operation says arrays have different shape

查看:381
本文介绍了DenseBase,自动和二进制操作表示数组具有不同的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个函数,该函数使用两个 DenseBase 作为参数。

I write a function that takes two DenseBase as arguments.

该函数使用 .derived()。array()转换两个 Array Matrix Array

The function uses .derived().array() to convert both Array and Matrix to Array.

我厌倦了多次编写派生的并使用自动。

I got tired of writing derived for many times and use auto.

但是自动会导致奇怪的错误。 Eigen抱怨 x2 y2 的形状不相同。

But auto leads to strange error. Eigen complains that x2 and y2 don't have same shape.

如果我不想多次写 .derived()。array(),我该怎么用?

If I don't want to write .derived().array() for many times, what can I use?

本征来自 https://github.com/eigenteam/ eigen-git-mirror.git

#include <Eigen/Eigen>
int main() {
    Eigen::ArrayXf x(3);
    Eigen::ArrayXf y(3);
    x << 1, 2, 3;
    y << 4, 5, 6;
    // x.derived().array() * y.derived().array();
    auto x2 = x.derived().array();
    auto y2 = y.derived().array();
    y2 = x2 * y2; 
}

运行时错误:

CwiseBinaryOp.h:110: ...

Assertion `aLhs.rows() == aRhs.rows() 
           && aLhs.cols() == aRhs.cols()' failed.


推荐答案

您可以使用<$ c $解决运行时问题c> auto x2 = x.array()。derived(); ,即:反向数组并派生。但是 auto 在这里不是可取的。这就是为什么。假设您有:

You can fix the runtime issue with auto x2 = x.array().derived();, that is: reverse array and derived. But auto is not desirable here. Here is why. Say you have:

template <typename T> void foo(DenseBase<T> &x);

如果 T Array<> ,然后 x.array()。derived() Array<> x2 将是 x 的深层副本。在这种情况下,您想使用 auto& x2 = ...

If T is an Array<> then x.array().derived() is an Array<> and x2 will be a deep copy of x. In this case you would like to use auto& x2 = ....

如果 T 是别的东西,例如 Matrix<> ,然后 auto x2 = x.array()。derived(); 很好,但是不是 auto& x2 = ...

If T is something else, e.g., a Matrix<>, then auto x2 = x.array().derived(); is perfectly fine, but not auto& x2 = ....

因此,您真正想要的东西很复杂:

So what you really want is something as complicated as:

internal::ref_selector<std::decay<decltype(x.array().derived())>::type>::non_const_type
  x2 = x.array().derived();

不好:(

一个简单解决方案是不要为创建数组世界中的输入而烦恼并创建 ArrayWrapper

A simpler solution is to not bother and create an ArrayWrapper even for inputs that are already in the array world:

ArrayWrapper<T> x2(x.derived());

另一个简单的解决方案是强制调用者在数组世界中传递表达式:

Yet another simple solution is to enforce the caller to pass expressions in the array world:

template <typename T> void foo(ArrayBase<T> &x) {
  T& x2(x.derived());
  ...
}

这篇关于DenseBase,自动和二进制操作表示数组具有不同的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆