I am working in C# with the Math.Net Numerics library and mainly using Vector<T> and Matrix<T> objects (doing linear regressions, finding eigenvalues, etc...). Mostly I'm working with complex numbers so I'm using Vector<Complex> (or matrix equivalent), but I also need to use Vector<Double> sometimes. My question is, therefore, how can I cast a Vector<Complex> to a Vector<Double>? Alternately, is there a way to get/set only the real (or imaginary) part of the whole Vector? I am doing this in C# which is a language I'm relatively new to (mostly I use C/C++ and MATLAB) so I apologize if this seems like a simple question.
Possible Examples:
Vector<Double> someDoubleVector; // already exists
Vector<Complex> someComplexVector; // ditto
double[] doubleArray; // ditto
double[] anotherDoubleArray; // ditto
someDoubleVector = someComplexVector.GetReal();
or
someDoubleVector = (Vector<Double>)someComplexVector;
or (setting just the real)
someComplexVector.SetReal(someDoubleVector);
or
someComplexVector.SetReal(doubleArray);
or when creating
Vector<Complex> anotherComplexVector = Vector<Complex>.Build.Dense(Vector<Double> realValues, Vector<Double> imagValues);
You can use the Map method to convert between the types. If you need this often, you could define the following extension methods:
static class VectorExtensions
{
public static Vector<double> Real(this Vector<Complex> v)
{
return v.Map(x => x.Real);
}
public static Vector<double> Imag(this Vector<Complex> v)
{
return v.Map(x => x.Imaginary);
}
}
And then simply call
var someDoubleVector = someComplexVector.Real();
The same approach would also work for other similar conversions.
Update 2015-12-30: this functionality has been integrated into Math.NET Numerics since v3.10.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With