2012-11-23 44 views
2

我有以下阵列优惠块

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 

当我在子数组上进行一些计算时,我想在大数组中进行计算。

比如我有一个Matrix类

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 

我已经超负荷了一些运营商如()/ * - +等,但我有我不知道绳拉可以操纵子阵列。

+1

如何'38.1558 44.5586 27.6923 31.7099'有关'(1,1)(2,2)子array' –

+0

我有一个很难理解怎么个其中4个数字是从(1,1)到(2,2)的子数组。那是什么符号? –

+0

对不起,我固定的,(起始行,起始列,结束行,结束列) –

回答

2
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函数返回一个SubMatrix针对operator =超载采取Matrix(和一个了结一个SubMatrix和可能的其他运营商,operator =Matrix采取SubMatrix等)。

然后,这个辅助类将在给定的窗口读取/写入原始矩阵。

+0

您的解决方案工作正常,现在我得到了一个不同的问题,当我想返回原单矩阵 '模板 矩阵子矩阵 :: getMatrix(){ \t return * origin; }'' 矩阵 TMP = m.getMatrix();',我发现了以下错误:使 'const的子矩阵' 作为 '这个' 矩阵” 子矩阵 :: getMatrix()的参数[其中T = double]'丢弃限定符 –

+0

它基本上说'm'是'const'。你的函数'getMatrix()'应该被定义为'... getMatrix()const;'。正如你所知道的,只有类型的'name(args)const''类的函数可以在'const'对象上被调用。 – Shahbaz

1

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

数值Python使用这样的设计取得了很大的成功。

0

如果你问如何写它,那是一回事。

如果你想要一个已经写好的解决方案,看看Boost的multi_array。您可以通过一些存储开销优化获得N维矩阵。

你使用特定的类boost::multi_array_refboost::const_multi_array_ref

(注:从经验公平的警告......这些都没有准备在这一点上的存储C++ 11只布展类型如unique_ptr时间)。

0

实际的问题是,你的矩阵类支持太多的操作。最低要求操作将是这样的:

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 
}; 

然后子矩阵是一个从MatrixI操作到MatrixI:

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; 
};