简体   繁体   中英

Flattening array from 2d to 1d

Let's say we have 2 arrays:

double[,] a = new double[width,height];
double[] b = new double[width*height];

We fill a with some numbers, let's say 0s and 1s.

Why does:

for(int i = 0; i < a.GetLength(0); i++)
    for(int j = 0; j < a.GetLength(1); j++)
        b[i * a.GetLength(0) + j] = a[i,j];

return only 0s in all fields of b[]?

By the way. A much more efficient way to convert your 2-d array to 1-d array is:

public static T[] ToPlainArray<T>(this T[,] array)
{
    Type type = typeof(T);
    int sizeInBytes = Marshal.SizeOf(type);
    T[] buffer = new T[array.Length];
    Buffer.BlockCopy(array, 0, buffer, 0, array.Length * sizeInBytes);
    return buffer;
}

Usage:

double[] b = a.ToPlainArray();

Or

double[] b = ToPlainArray(a);

You need to multiply by the length of the second dimension, not the first:

b[i * a.GetLength(1) + j] = a[i,j];

Beyond that, there are less efficient but harder to mess up ways of doing this:

b = a.Cast<double>.ToArray();

Add the following line:

Debug.WriteLine("b[" + (i* a.GetLenth(1) + j) + "] = " + b[i * a.GetLength(1) + j]);

and check what happens

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM