0

我正在尝试将两个不同的稀疏矩阵相加,以实现一个大矩阵,其中包含来自另一个矩阵的所有值。但是,如果它们在特定键处都有值,则应将这些值相加。我不知道如何引用正在创建的新矩阵,以便我可以将新的新值放入其中然后返回。

4

1 回答 1

0

我会建议这样的东西 - 请注意,这是未经测试的代码。

public static SparseMatrix add(SparseMatrix a, SparseMatrix b) {
  if (a.rows != b.rows || a.cols != b.cols) {
    // They must be the same dimensions.
    return null;
  }
  return new SparseMatrix(a.rows, a.cols).add(a).add(b);
}

private SparseMatrix add(SparseMatrix a) {
  // Walk all of his.
  for (Integer i : a.matrix.keySet()) {
    // Do I have one of these?
    if (matrix.containsKey(i)) {
      // Yes! Add them together.
      TreeMap<Integer, Double> mine = matrix.get(i);
      TreeMap<Integer, Double> his = a.matrix.get(i);
      // Walk all values in there
      for (Integer j : his.keySet()) {
        // Do I have one of these?
        if (mine.containsKey(j)) {
          // We both have this one - add them.
          mine.put(j, mine.get(j) + his.get(j));
        } else {
          // I do not have this one.
          mine.put(j, his.get(j));
        }
      }
    } else {
      // I do not have any of these - copy them all in.
      matrix.put(i, new TreeMap(a.matrix.get(i)));
    }
  }
  return this;
}
于 2013-11-17T16:47:08.823 回答