Hi everyone,
I wanted to share a trick I just discovered as an alternative way to use loops when iterating over a 2D array.
So let’s say you have a 2D Array Initializated like this:
public void CreateMatrix(int size){
float [,] arr = new float[size, size];
}
Let’s say you want to initialize it with every number set to one, the usual approach should be like:
public void CreateMatrix(int size){
float [,] arr = new float[size, size];
for (int i = 0; i < size; i++){
for (int j = 0; j < size; j++){
arr[i,j] = 1;
}
}
}
Instead of using two for-loops to get the element of an array, you could simply use one loop which is much faster than nested loops.
public void CreateMatrix(int size){
float [,] arr = new float[size, size];
for (int i = 0; i < size * size; i++){
int row = i / size; // Note that this is integer division..
int col = i - row * size;
arr[row, col] = 1;
}
Note that there is an integer division at line 4, later the variable assigned (row) is multiplied with the size parameter, thus they dont cancel each other.
This approach also works for rectangular Arrays, in that case the code would be like:
public void CreateMatrix(int rows, int columns){
float [,] arr = new float[rows, columns];
for (int i = 0; i < rows * columns; i ++){
int row = i / columns;
int column = i - row * columns;
arr [row, column] = 1;
}
}
Note that this approach is running through columns first and rows later like the first example of this diagram (from wikpedia):

Example: Identity Matrix Initilization:
public float[,] Identity(int size){
float[,] arr = new float[size, size];
for (int i = 0; i < size * size; i++){
int row = i / size;
int column = i - row * size;
if (row == column){
arr[row, column] = 1;
}else{
arr[row, column] = 0;
}
return arr;
}
EDIT: I changed the title because I’ve just realized that this methos is not efficient for large arrays (1000 x 1000), in that case ested loops are a better option. This method works well with small arrays though.