我正在做一些非常基础的线性代数,我可能完全忽略了这里的要点。
假设我有以下矩阵:
v1 = [5, 8]
v2 = [3, 4]
v3 = [4, 4]
v4 = [2, 1]
预期输出:
M1 = [5 - 3, 8 - 4] = [2, 4]
M2 = [4 - 2, 4 - 1] = [2, 3]
实际输出:
0 0
0 0
2 4
-1 0
2 3
代码如下:
std::vector<double> calculate(std::vector<double> values, std::vector<double> values2)
{
std::vector<double> vel(2, 0);
for(unsigned i=0; (i < values.size()); i++)
{
vel[i] = values[i] - values2[i];
}
return vel;
}
std::vector<std::vector<double> > values = { {5,8}, {3, 4}, {4, 4}, {2, 1}};
std::vector<std::vector<double> > v;
v.resize(2);
for(unsigned i=0; (i < values.size()-1); i++)
{
v[i].resize(2);
v.push_back(calculate(values[i], values[i + 1]));
//v[i] = calculate(values[i], values[i + 1]);
}
for(unsigned i=0; (i < v.size()); i++)
{
for(unsigned j=0; (j < v[i].size()); j++)
{
std::cout << v[i][j] << " ";
}
std::cout << std::endl;
}
问题是,下面应该迭代 4 次以上,计算 4 个矩阵,最终生成的 2D vector 应该只包含 2 个值。
我可能遗漏了一些愚蠢的东西。
最佳答案
v.resize(2); // now it contains `{{} {}}`.
for(unsigned i=0; (i < values.size()-1); i++) //for each input except the last (3 iterations)
//starting with {5,8} and {3,4}
v[i].resize(2); //resize one of the vectors already in v to 2
//now v contains {{0,0}, {}
v.push_back(calculate(values[i], values[i + 1])); //push back the calculations
//now v contains {{0,0}, {}, {2,4}}
for(............. (i < values.size()-1); i++)
//next the middle pair of inputs {3,4} and {4,4}
v[i].resize(2); //resize one of the vectors already in v to 2
//now v contains {{0,0}, {0,0}, {2,4}}
v.push_back(calculate(values[i], values[i + 1])); //push back the calculations
//now v contains {{0,0}, {0,0}, {2,4}, {-1,0}}
for(............. (i < values.size()-1); i++)
//finally the last pair of inputs {4,4} and {2,1}
v[i].resize(2); //resize the {2,4} to 2, but it was already two
//now v contains {{0,0}, {0,0}, {2,4}, {-1,0}}
v.push_back(calculate(values[i], values[i + 1])); //push back the calculations
//now v contains {{0,0}, {0,0}, {2,4}, {-1,0}, {2,3}}
for(............. (i < values.size()-1); ....) //done iterating
你有调试器吗?学习如何像这样单步执行代码、请人向您展示或查找教程非常重要。在调试器中逐步执行此代码会使您清楚地知道发生了什么。
幸运的是,代码很容易修复:
std::vector<std::vector<double> > v;
for(unsigned i=0; i<values.size()-1; i+=2) //NOTE: i+=2!!!
{
v.push_back(calculate(values[i], values[i + 1]));
}
关于C++ - 矩阵减法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21895396/