简体   繁体   English

添加两个sparsematrix树图

[英]Adding two sparsematrix treemaps

I'm trying to add two different sparse martices together to achieve one large matrix with all the values from the other matrix. 我正在尝试将两个不同的稀疏刻痕相加在一起,以实现一个大矩阵,并具有来自另一个矩阵的所有值。 But if they both have a value at a specific key, the values should be added together. 但是,如果它们在特定键上都有值,则应将这些值加在一起。 What I can't figure out is how to reference the new matrix that is being created so I can put new the new values into it to then return. 我不知道如何引用正在创建的新矩阵,因此可以将新的新值放入其中,然后返回。

I would suggest something like this- note that this is untested code. 我会建议这样的东西-请注意,这是未经测试的代码。

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM