如何就地修改一维数组的每个元素? [英] How do I in-place modify each element of a 1D Array?

查看:82
本文介绍了如何就地修改一维数组的每个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双精度的一维本征数组( Eigen :: Array< double,Dynamic,Dynamic> ),我想修改数组就地。但是,我不太确定该怎么做。我正在考虑:

I have a 1D eigen array (Eigen::Array<double,Dynamic,Dynamic>) of doubles, and I want to modify each element in the array in place. However, I'm not really sure how to do this. I'm considering this:

Eigen::Array<double,Eigen::Dynamic,Eigen::Dynamic> arr1D;
// ...

// Threshold function:
arr1D.unaryExpr([](double& elem)
{
    elem = elem < 0.0 ? 0.0 : 1.0;
}
);

但这似乎有点hack,因为特征参考示例仅给出 .unaryExpr 的示例。一个返回值的函子(然后整个方法只返回另一个数组)。就我而言,我希望避免创建新数组。

But this seems like a bit of a hack because the Eigen Reference examples only give examples of .unaryExpr where it is used with a functor that returns a value (and then the whole method just returns a different array). In my case, I was hoping to avoid the need for creating a new array.

我是Eigen的新手,所以我想我可能会在这里遗漏一些东西,输入是

I'm new to Eigen so I thought I might be missing something here, input is appreciated.

编辑:我知道我可以简单地用 arr1D = arr1D> = 0.0 ,但请注意,这只是一个示例

I understand that I can replace the above simply with arr1D = arr1D >= 0.0, but please note that this is just an example

推荐答案

.unaryExpr 将视图返回给由给定函数转换的原始数据。

.unaryExpr returns "view" to original data transformed by given function. It doesn't do transformation of original data.

您不能更改传递给转换函数的参数。仅由于尚未触发适当代码的模板实例化而编译代码。如果将结果分配给值,则编译失败:

You cannot change argument passed to transformation function. Your code is compiled only because you have not triggered template instantiation of appropriate code. If assign result to value then it fails to compile:

#include <Eigen/Dense>

int main()
{
    using namespace Eigen;

    ArrayXd x, y;
    y = x.unaryExpr([](double& elem)
    {
        elem = elem < 0.0 ? 0.0 : 1.0;
    }); // ERROR: cannot convert const double to double&
}

错误的确切位置在 Eigen 内部:

Exact place of error is in Eigen internals:

EIGEN_STRONG_INLINE const Scalar coeff(Index index) const
{
  return derived().functor()( derived().nestedExpression().coeff(index) );
  //     ^^^^^^^^^^^^^^^^^^^ - your lambda
}






我认为使用 Eigen 进行原位处理的最简单方法是:


I think the easiest way to do in-place with Eigen is:

ArrayXd x = ArrayXd::Random(100);
x = x.unaryExpr([](double elem) // changed type of parameter
{
    return elem < 0.0 ? 0.0 : 1.0; // return instead of assignment
});

unaryExpr 不返回完整的新数组/矩阵-但它会返回行为类似于它的特殊临时对象。

unaryExpr does not return full new array/matrix - but it returns special temporary object which acts like it.

这篇关于如何就地修改一维数组的每个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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