Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialise array of tuples of float arrays of known length

I have got hardware that sends two float arrays of data of the same length when requested. The array length of the floats is known as soon as the hardware is initalised in the program and is fixed thereafter.
I am now sending multiple requests to the device and want to save the data to transmit all received data to another device at once later. Before sending all requests I already know the number of requests that are going to be sent. I therefore thought of using a tuple array of float arrays to store the data. How do I initialise this? I tried something like this

(float[] x, float[] y)[] MyData = new (new float[dataLength], new float[dataLength])[NumberOfRequests]

but it’s not working. I thought of doing it like this:

internal class Data
{
    public float[] x;
    public float[] y;

    public Data(int Length)
    {
        x = new float[Length];
        y = new float[Length];
    }
}

internal static class AllData
{
    public static Data[] CreateEmpty(int length, int requests)
    {
        Data[] Result = new Data[requests];
        for (int i = 0; i < requests; i++)
        {
            Data d = new Data(length);
            Result[i] = d;
        }

        return Result;
    }
}

but I believe that looping over all elements is probably not very efficient. I obviously could use a list, but since I know the number of elements before actually filling them I thought an array would be more performant. Is there a better/correct way of doing this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Willy-nilly you have to initialize each item, if you don’t like loop, you can try Linq:

using System.Linq

...

(float[] x, float[] y)[] MyData = Enumerable
  .Range(0, NumberOfRequests)
  .Select(_ => (new float[dataLength], new float[dataLength]))
  .ToArray();

Or (same idea with Data class)

public static Data[] CreateEmpty(int length, int requests) {
  ArgumentOutOfRangeException.ThrowIfNegative(length);
  ArgumentOutOfRangeException.ThrowIfNegative(requests);

  return Enumerable
    .Range(0, requests)
    .Select(_ => new Data(length))
    .ToArray();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading