简体   繁体   中英

built-in function diff() available for vector in MathNet?

I'm new to MathNet and implementing a code in C#.Net .

There is a vector:

var X = new DenseVector(new double[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150 });

I need to find Y = **diff(X)** calculating differences between adjacent elements of X like:

Y = [X(2)-X(1) X(3)-X(2) ... X(m)-X(m-1)]

Is there built-in function diff() available in MathNet ? I searched on MathNet.Numerics/Differentiate , but its not available.

You are correct. It does not appear to be available. But here is a simple function to achieve that.

public MathNet.Numerics.LinearAlgebra.Double.DenseVector 
Diff(MathNet.Numerics.LinearAlgebra.Double.DenseVector X)
{
    var R = new MathNet.Numerics.LinearAlgebra.Double.DenseVector(X.Count - 2);
    for (var i = 0; i <= X.Count - 2; i++)
        R(i) = X(i + 1) - X(i);
    return R;
}

You can use advantages of MathNet to make it more expressive.

static class VectorExtension
{
    public static Vector<double> Differentiate(this Vector<double> vector)
    {
        var high = Vector<double>.Build.DenseOfEnumerable(vector.Skip(1));
        var low = Vector<double>.Build.DenseOfEnumerable(vector.Take(vector.Count - 1));
        return  high - low;
    }
}

Then

var X = new DenseVector(new double[] { 10, 20, 30, 40, 50, 60, 70 });
Console.WriteLine(X.Differentiate());

Gives

DenseVector 6-Double
10
10
10
10
10
10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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