2016-10-02 222 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,好吧。請參閱更新。 –