Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 333
Marcel Gangwisch Avatar asked Jan 30 '19 14:01

Marcel Gangwisch


People also ask

What is a Vector3 in C?

What is a Vector3 in C? It is representation of 3D vectors and points, used to represent 3D positions,considering x,y & z axis.01-Feb-2019.

What is vector data structure c#?

Informally, a vector is an array of numeric values. A matrix is conceptually a two-dimensional data structure of numeric values. The demo program begins by creating and displaying a vector with four cells, each initialized to 3.5. Next, the demo creates a 3x4 (3 rows, 4 columns) matrix.


1 Answers

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.

like image 101
Daniel A. White Avatar answered Oct 16 '22 11:10

Daniel A. White