Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to zero out a 2D array in C#

I have a 2D array that I want to clear and reset to 0 values. I know how to clear a vector (1D array) using Array.Clear() but I don't know the best way to clear a 2D matrix.

double D = new double[10];  
Array.Clear(D, 0, D.Length);

How does one clear a 2D N x M array

double D[,] = new double[N,M];

Thank you for any help you may be able to provide.

like image 743
PBrenek Avatar asked Oct 29 '13 21:10

PBrenek


2 Answers

Array.Clear works with multidimensional arrays, too:

double[,] D = new double[M,N];
Array.Clear(D, 0, D.Length);

Note, there's no need to compute the length yourself, since the Length property returns the total number of elements, regardless of the number of dimensions:

A 32-bit integer that represents the total number of elements in all the dimensions of the Array; zero if there are no elements in the array.

like image 103
p.s.w.g Avatar answered Oct 08 '22 10:10

p.s.w.g


You can use the same method, but you may have to calculate your real length parameter value:

double D[,] = new double[N,M];
Array.Clear(D, 0, M*N);

I would use M*N because it's more readable, and I don't know what Length property returns for 2-dimmentional array.

like image 1
MarcinJuraszek Avatar answered Oct 08 '22 11:10

MarcinJuraszek