I’m working on a little matrix class for my own use and because for me, it is just fun!
Now I noticed a lot (10 and more) of the methods always seem to follow the same pattern:
- Iterate over the rows
- For each row iterate over the columns
- Do something with each element of the matrix
An example:
// <returns>the zero matrix</returns>
public static MMatrix Zero(int row, int col)
{
MMatrix MA = new MMatrix(r, c);
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
MA[i, j] = 0;
}
}
return MA;
}
I asked myself if I could get rid of the nested for loops in all those methods.
So, I tried to improve on this, thanks to the wonders of C# by using an Action delegate:
public void Iterate(int rows, int cols, Action<int, int> A)
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
A.Invoke(i,j);
}
}
}
Now my Zero matrix method becomes:
public static ReMatrix Zero(int r, int c)
{
ReMatrix MA = new ReMatrix(r, c);
MA.Iterate(r, c, (x, y) => { MA[x, y] = 0; });
return MA;
}
I would like to ask you all, if this is an improvement?
Or is it better to stay with the nested for loops.