Howto在C 中使用MATLAB和STL矢量的操作员

Howto use matlab like operator in C++ with stl vector

本文关键字:STL 操作员 MATLAB Howto      更新时间:2023-10-16

在matlab中,我们可以使用MATLAB操作员如下:

M=[1 2 3 4, 5 6 7 8, 9 10 11 12]
M[:,1] = M[:,2] + M[:,3]

将相同的操作应用于矩阵的所有行我想知道我们是否可以应用相同的操作将值设置为std::vector中的一个值范围的范围(:) Matlab的运算符。确实,我正在使用向量存储矩阵值。

vector<int> M;

预先感谢。

有C 库可以像MATLAB一样处理矩阵(也允许 simd vectorization);例如,您可能要考虑特征。

如果您不想依靠外部库,则可能需要考虑明确考虑代数计算的std::valarray(使用valarray S,您可以使用std::slices根据需要提取子膜片)。

您可以定义将std::vector<int>作为参数的"免费"操作员:

std::vector<int> operator +(const std::vector<int> &a, const std::vector<int> &b)
{
    std::vector<int> result(a); // Copy the 'a' operand.
    // The usual matrix addition is defined for two matrices of the same dimensions.
    if (a.size() == b.size())
    {
        // The sum of two matrices a and a, is computed by adding corresponding elements.
        for (std::vector<int>::size_type i = 0; i < b.size(); ++b)
            // Add the values of the 'b' operand.
            result[i] += b[i];
        return result;
    }
}
int main(int argc, char **argv)
{
    std::vector<int> a;
    std::vector<int> b;
    // The copy constructor takes care of the assignement.
    std::vector<int> c(a + b);
    return 0;
}

operator +的实现非常天真,但只是一个想法。当心!,我在添加操作之前放了一个ckeck,如果没有通过支票返回a操作数的副本,我认为这不是您所需的行为。

我已经将操作员放在main的同一文件中,但是只要在执行操作的情况下可见,您都可以将其放置在任何地方。

当然,您可以定义所需的操作员以实现一些更复杂的操作。

我的数学概念很老,但我希望它会有所帮助。