如何减去两个稀疏矢量?

时间:2016-10-02 23:54:06

标签: java vector colt

我刚接触SparseVector。我想减去两个SparseVectors并将结果返回为SparseVector

VectorSparseVector之间的区别是什么?

我尝试从定义函数开始,该函数需要两个SparseVector,但没有得到帮助我的东西!

import java.awt.Point;
import java.util.HashMap;
import cern.colt.list.DoubleArrayList;
import cern.colt.matrix.impl.SparseDoubleMatrix1D;

public class SparseVector extends SparseDoubleMatrix1D {
    public SparseVector(int size) {
        super(size);
    }

    public SparseVector(double[] values) {
        super(values);
    }

    public  SparseVector subtract(SparseVector v1, SparseVector v2) {
        // TODO: How to implement it?
    }
}

1 个答案:

答案 0 :(得分:0)

似乎没有必要创建自定义实现。请考虑以下示例:

import cern.colt.matrix.impl.SparseDoubleMatrix1D;
import cern.jet.math.Functions;

final class SparseVector extends SparseDoubleMatrix1D {
    public SparseVector(int size) {
        super(size);
    }

    public SparseVector(double[] values) {
        super(values);
    }

    /**
     * Subtract otherVector from this vector.
     * The result is stored in this vector.
     * @param otherVector other vector
     * @return this vector
     */
    public SparseVector subtract(SparseVector otherVector) {
        assign(otherVector, Functions.minus);
        return this;
    }

    public static SparseVector subtract(SparseVector x, SparseVector y) {
        final SparseVector result = new SparseVector(x.toArray());
        result.subtract(y);
        return result;
    }
}

请参阅cern.jet.math.Functions class

自定义实施

请注意,静态方法可能是多余的。

final SparseVector aVector = new SparseVector(new double[] { 3.0 });
final SparseVector bVector = new SparseVector(new double[] { 1.0 });

aVector.subtract(bVector);

// aVector is the result.
System.out.println(aVector);

示例:

 public ActionResult Index() {
        var listAll = db.Reviews.Include(m => m.User);
        return View(listAll.ToList());           
  }