Howto在C 中使用MATLAB和STL矢量的操作员
Howto use matlab like operator in C++ with stl vector
在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
的同一文件中,但是只要在执行操作的情况下可见,您都可以将其放置在任何地方。
当然,您可以定义所需的操作员以实现一些更复杂的操作。
我的数学概念很老,但我希望它会有所帮助。
相关文章:
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 在C应用程序中运行C++(带有STL)函数
- 使用2个键的cpp-stl::优先级队列排序不正确
- 在STL容器中使用模板类
- <<操作员在下面的行中工作
- 用C++中的CPerson(类)类型的对象初始化STL矢量
- 将stl字符串缩小到小于15个字符的容量
- 在为LINUX创建共享库时,如何避免STL的私有/弱副本
- 检查函数返回类型是否与STL容器类型值相同
- STL算法函数在多个一维容器上的使用
- 在STL - C++中按成绩对学生列表进行排序?
- C++ 与操作员不匹配<<
- 操作员C++的模棱两可的过载
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- λ可以适应STL吗?
- C STL,我想知道地图中的双向迭代器和操作员[]之间有什么不同
- 当我使用STL集时,我应该超载==操作员吗?
- Howto在C 中使用MATLAB和STL矢量的操作员
- STL 减少操作员和"invalid operator<"误差