2016-10-02 119 views
-1

我是新来处理SparseVector。我想要减去两个SparseVectors并返回结果为SparseVector如何减去两个sparsevector?

VectorSparseVector有什么区别?

我试着用define函数开始,这个函数需要两个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? 
    } 
} 
+0

能否请您发布目前实施的'SparseVector'类的?您能否指出'subtract()'方法的预期语义是什么? –

+0

我定义的方法减去让我在另一个类中调用它,它将采用两个稀疏向量来返回一个稀疏向量中的结果 – user1

+0

该方法应该是“静态”吗? –

回答

0

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

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

// … 

final SparseDoubleMatrix1D aMatrix = new SparseDoubleMatrix1D(new double[] { 3.0 }); 
final SparseDoubleMatrix1D bMatrix = new SparseDoubleMatrix1D(new double[] { 1.0 }); 
aMatrix.assign(bMatrix, Functions.minus); 
// aMatrix is the result. 
System.out.println(aMatrix); 

请参阅cern.jet.math.Functions class

自定义实现

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

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

例子:

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); 
+0

谢谢,但我需要一个方法,因为我说我有两个稀疏向量在另一个类有价值,我需要减去他们 – user1

+0

@ user1,好吧。请参阅更新。 –