C++减少矩阵的维度

标签 c++ matrix dimensions

我遇到了以下问题:我有一个 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/

相关文章:

c++ - 像访问一维数组一样访问二维数组是否合法?

由自定义缓冲区支持的 C++ 固定大小 vector

r - 如何将单列转换为R中的矩阵

math - 在 Julia 中有效地向矩阵添加标量

google-analytics - 仅使用一个自定义维度和一个自定义指标跟踪 GA 中的所有内容

c++ - 如何有效查找大型 std::map

c++ - 未定义对我的函数的引用

python - Matplotlib python 在颜色图中更改单一颜色

iphone分辨率问题

excel - 自动插入冒号(:) in multiple columns under the Options Explicit