PBrenek
PBrenek

Reputation: 571

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.

Upvotes: 19

Views: 25998

Answers (3)

p.s.w.g
p.s.w.g

Reputation: 149058

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.

Upvotes: 43

MarcinJuraszek
MarcinJuraszek

Reputation: 125660

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.

Upvotes: 1

NebulaSleuth
NebulaSleuth

Reputation: 841

Just reallocate it.

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

creates a empty 2D array.

Upvotes: -1

Related Questions