2

是的,以前已经做过一百万次了,但该死的,我还想再做一次。我正在为 C++ 编写一个简单的矩阵库,目的是做。我遇到了一些在数学中相当明显的东西,但对于强类型系统来说并不那么明显——事实上,1x1 矩阵只是一个数字。为了避免这种情况,我开始沿着矩阵的毛茸茸的路径作为向量的组合,但也偶然发现了一个事实,即两个向量相乘可能是一个数字或一个对,这取决于两者的方向。

我的问题是,在 C++ 或 Java 等强类型语言中处理这种情况的正确方法是什么?

4

3 回答 3

3

something that's fairly obvious in mathematics, but not so obvious to a strongly typed system -- the fact that a 1x1 matrix is just a number.

That's arguable. A hardcore mathematician (I'm not) would probably argue against it, he would say that a 1x1 matrix can be regarded as isomorphic (or something like that) to a scalar, but they are conceptually different things. Only in some informal sense "a 1x1 matrix is a scalar" (similar, though stronger, that a complex number without an imaginary part "is a real").

I don't think that that correspondence should be reflected in a strong typed language. And I dont' think it is, in typical implementations (of complex or matrix), eg. Java Apache Commons Math. For example, a Complex with zero imaginary part is not a Number (from the type POV - they cannot be casted one into another).

In the case of matrices, the correspondence is even more disputable. Should we be able to multiply two matrices of sizes (4x3) x (1x1) ? If we regard the second as a scalar, it's valid, but not as a matrix, since it violates the restriction on matrix dimensions for multiplication. And I believe Commons sticks to that.

In a weakly typed language (eg Matlab) it would be another story.

于 2010-06-05T12:27:55.627 回答
2

如果您不担心 SIMD 优化等,那么我认为最好的方法是设置模板化张量。选择您的最大张量维度,然后您可以执行以下操作:

typedef Tensor3D< float, 4, 1, 1 > Vector4;

等等。如果正确实施,数学将适用于所有形式的“矩阵”和“向量”。毕竟,两者都只是张量的特例。

编辑:知道模板的大小实际上很容易。添加 GetRows() 等函数,您可以在实例化时返回传递给模板的值。

IE

template< typename T, int rows, int cols > class Tensor2D
{
public:
    int GetRows() { return rows; }
    int GetCols() { return cols; }
};
于 2010-06-05T08:01:34.853 回答
0

我的建议?不用担心 1x1 的情况,晚上睡觉。您不必担心突然决定使用您的库将一堆数字建模为 1x1 矩阵并抱怨您的实现的任何用途。

解决这些问题的人不会如此愚蠢。如果您足够聪明地使用矩阵,那么您就足够聪明地正确使用它们。

至于标量引入的所有排列,我想说你必须考虑它们。作为矩阵库用户,我希望能够将两个矩阵相乘以获得另一个矩阵,一个矩阵乘以一个(列或行)向量得到一个向量结果,一个标量乘以一个矩阵得到另一个矩阵。

如果我将两个向量相乘,我可以得到一个标量(内积)或矩阵(外积)。你的图书馆最好把它们给我。

这不是微不足道的。其他人已经“正确”地完成了它,但为自己完成它而感到自豪。

于 2010-06-05T12:56:44.630 回答