user1
user1

Reputation: 499

How to subtract two sparsevector?

I'm new to dealing with SparseVector. I want to subtract two SparseVectors and return result as SparseVector too.

What is the difference between Vector and SparseVector?

I tried to start with define function that take two SparseVector but didn't get antything that helped me!

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

Upvotes: -1

Views: 640

Answers (1)

It seems there is no need to create a custom implementation. Please consider the following example:

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

Please refer to the cern.jet.math.Functions class.

Custom implementation

Note that the static method may be redundant.

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

Example:

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

Upvotes: 0

Related Questions