Search code examples
c#vectorcountsystem.numerics

How to get the elements of a System.Numerics.Vector in C#?


I want to access the elements of a System.Numerics.Vector<T> in C#. I'm following the official documentation: https://learn.microsoft.com/en-us/dotnet/api/system.numerics.vector-1?view=netcore-2.2

I'm able to create different vectors with different datatypes. For example: var test = new Vector<double>(new double[] { 1.0, 2.0, 1.0 });

But now I have the problem, that I'm unable to call test.Count; it is not possible to call Count on an instance of type System.Numerics.Vector<T>.

I can access single elements with the access operator [], but I dont know how many elements are in the vector.

According to the documentation, there should be the public property:

public static int Count { get; }

But I can not call in on my instance of System.Numerics.Vector<T>. Instead I can call it only in a static manner like following:

Vector<double>.Count

This is equal to 2.

I can also call:

Vector<Int32>.Count

returning: 4 and

Vector<Int16>.Count

returning 8.

And now I'm really a bit confused, about how to use this static property. At first, I thought, that this property would return the number of elements stored in the vector (as stated in the documentation). Second, I thought, that this property returns the size of the vector in memory, but this number increases from double to Int32 to Int16.

Interestingly I can not call this static property from my instance created by:

var test = new Vector<double>(new double[] { 1.0, 2.0, 1.0 });

I can not call test.Count!

Do you know how to access the elements of System.Numerics.Vector<T>?


Solution

  • There is no way to do that. Vector<T> is of a fixed size, since it's trying to optimize for hardware acceleration. The docs state:

    The count of a Vector<T> instance is fixed, but its upper limit is CPU-register dependent. It is intended to be used as a building block for vectorizing large algorithms.

    Reading the source at https://source.dot.net/#System.Private.CoreLib/shared/System/Numerics/Vector.cs

    Shows that it will throw if less data is passed in that's required and will only take up to Count of items passed in.