mathnet-numerics
mathnet-numerics copied to clipboard
Append two Vectors in mathnet-numerics
Hi 😊 I am using the ODE solvers in mathnet-numerics to solve a system of ODE, and I have encountered several times that I need to append two vectors along the same axis. In numpy I would write something like this:
>>> np.append([1, 2, 3], [4, 5, 6])
array([1, 2, 3, 4, 5, 6])
Currently, the Vector type does not have an Append() method, so to append the two vectors I have to turn them to the Matrix type (as a row/column matrix). Then, since the ODE solver accepts Vector types, I need to transform the appended vectors from matrix type to vector type for the next iteration of the solver. Since this is a bit tedious, I wrote a method to append two vectors directly, which I consume within my projects.
Since I have encountered several use cases for this method, it might be interesting to include it within the Vector type. If you think this could be relevant, I'd be happy to open a pull request 😊
https://github.com/paucablop/paucablop.mathnet.vector.operations
And you can find the code here:
public static Vector<T> Append<T>(Vector<T> left, Vector<T> right) where T : struct, IEquatable<T>, IFormattable
{
if (left == null)
{
throw new ArgumentNullException(nameof(left));
}
if (right == null)
{
throw new ArgumentNullException(nameof(right));
}
Vector<T> vector = Vector<T>.Build.SameAs(left, left.Count + right.Count);
left.Storage.CopySubVectorTo(vector.Storage, 0, 0, left.Count, ExistingData.AssumeZeros);
right.Storage.CopySubVectorTo(vector.Storage, 0, left.Count, right.Count, ExistingData.AssumeZeros);
return vector;
}
Thanks a lot 😊
Good proposal in my view. I would just like to point out to small technical differences to the analogous (existing) implementation for matrices:
- Implemented as an instance method, not as a static method, which removes the necessity to check the left argument for null, and avoids the repetition of the type contraints.
- There is an additional overload, which takes a predefined result buffer as further argument and returns void.