从数组中获取一个块

Get a block from an array

本文关键字:一个 数组 获取      更新时间:2023-10-16

>我有以下数组

   75.7740   70.6046   82.3458   43.8744   48.9764
   74.3132    3.1833   69.4829   38.1558   44.5586
   39.2227   27.6923   31.7099   76.5517   64.6313
   65.5478    4.6171   95.0222   79.5200   70.9365
   17.1187    9.7132    3.4446   18.6873   75.4687

我想获取例如从 (1,1) 到 (2,2) 子数组

3.1833   69.4829  
27.6923   31.7099 

当我对子数组进行一些计算时,我也想在大数组中产生影响。

例如,我有一个矩阵类

template<class T>
class Matrix {
private:
    unsigned rows, cols;
    T* data_;
        .....
}

测试

MatrixXd u(5, 5);
MatrixXd d(2, 2);
....
u.subblock(1,1,2,2) = d*d
or
u(1,1,2,2) = d*d

我已经重载了一些运算符,如 ()/*-+ 等,但我不知道我可以操作子数组。

u.subblock(1,1,2,2) = d*d

要获得如上述工作这样的行,您可以定义一个帮助程序类:

template<class T>
class SubMatrix {
private:
    Matrix<T> *origin;
    unsigned int sr, sc, er, ec; // start and end row and column
        .....
};

然后,您的 Matrix::subblock 函数返回一个SubMatrixoperator = 已重载,需要Matrix(一个采用SubMatrix和可能的其他运算符,以及一个operator = Matrix采用SubMatrix等)。

然后,此帮助程序类将在给定窗口中读取/写入原始矩阵。

一种可能的设计是让子矩阵成为主矩阵相关部分的视图。换句话说,视图不会管理自己的存储,而是简单地重用主矩阵的存储。当视图被修改时,主矩阵也会被修改。

Numeric Python使用这样的设计取得了巨大的成功。

如果你问怎么写,那是一回事。

如果您想要已经编写的解决方案,请查看 Boost 的multi_array。 您可以获得这一点以及具有一些存储开销优化的 N 维矩阵。

您将使用的特定类是 boost::multi_array_ref 和 boost::const_multi_array_ref

(注:经验警告...目前,这些类型尚未准备好存储C++11 仅移动类型(如unique_ptr)。

实际问题是你的矩阵类支持太多的操作。所需的最低操作如下所示:

class MatrixI {
public:
  virtual int SizeX() const=0;
  virtual int SizeY() const=0;
  virtual float Map(int x, int y) const=0;
}

因此,为了使它正常工作,您应该基于上述接口实现操作 +,* 等:

class Matrix {
public:
   /* +,* -operations here */
private:
   MatrixI *ptr; // owned ptr
};

然后子矩阵是从矩阵I到矩阵I的操作:

class SubMatrix : public MatrixI {
public:
SubMatrix(MatrixI *orig, int pos_x, int pos_y, int sx, int sy);
/* implement minimum required functions here */
private:
  MatrixI *orig;
  int pos_x, pos_y;
  int sx,sy;
};
相关文章: