我遇到了以下问题:我有一个 9x9 矩阵,我想将其缩减为 5x5 矩阵。我想通过取消最后 3 行和列以及取消第 3 行和列来实现这一点。 我的代码看起来像这样。但它不能正常工作。
for (int A=0;A<6;A++)
for (int B=0;B<6;B++)
if ((A!=2) || (B!=2))
disshess5x5(A,B) = disshessian(A,B);
最佳答案
明确说明您要实现的内容总是明智的,因此它应该易于阅读。
在此示例中,您应该定义要跳过的行和列:
const bool rowToSkip[9] = { false, false, true, false, false, false, true, true, true, true };
const bool colToSkip[9] {...};
正如已经回答的那样,您还应该定义源到目标索引映射:
const int tgtRow[9] = {0,1,2,-1,3,4}; // and in the same way tgtCol
有了这样的常量,你会得到干净的循环,很容易发现任何错误:
for(int i = 0; i < 9; ++i)
if(!rowToSkip[i])
for (int j = 0; j < 9; ++j)
if(!colToSkip[j])
tgtMatrix[tgtRow[i]][tgtCol[j]] = srcMatrix[i][j];
[更新]
也可以通过定义目标->源索引以更快的方式完成:
const int srcRow[5] = {0,1,3,4,5};
const int srcCol[5] = {0,1,3,4,5};
for(int i = 0; i < 5; ++i)
for (int j = 0; j < 5; ++j)
tgtMatrix[i][j] = srcMatrix[srcRow[i]][srcCol[j]];
顺便说一句 - 你的范围 [0,6)
是 length == 6
- 你应该使用 [0,5)
范围满足 5x5
矩阵
关于C++减少矩阵的维度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31787575/