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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With