## Matrix Functions in C# for Machine Learning

The C# language is the most common language used by many enterprise developers who use the Microsoft technology stack. The Python language is very common for researchers and engineers who write machine learning code. I intend to refactor some Python code to C#. Python has all kinds of built-in functions that are useful for ML but for C#, you have to write several helper functions.

For example, it’s useful to have routines to create a matrix from an array, print a matrix, matrix multiplication, and so on.

Here’s a way to create a matrix from a C# array:

```static float[][] ArrayToMatrix(float[] arr, int rows, int cols)
{
float[][] result = new float[rows][];
for (int i = 0; i < rows; ++i)
result[i] = new float[cols];

int k = 0;
for (int i = 0; i < rows; ++i)
for (int j = 0; j < cols; ++j)
result[i][j] = arr[k++];

return result;
}
```

Note that 32-bit type float is more common than 64-bit type double. Here’s a way to print a matrix:

```static void Print(float[][] matrix, int dec)
{
for (int i = 0; i < matrix.Length; ++i) {
for (int j = 0; j < matrix[0].Length; ++j) {
Console.Write(matrix[i][j].ToString("F" + dec) + " ");
}
Console.WriteLine("");
}
}
```

And matrix multiplcation:

```static float[][] MatrixProduct(float[][] a, float[][] b)
{
int aRows = a.Length; int aCols = a[0].Length;
int bRows = b.Length; int bCols = b[0].Length;
if (aCols != bRows)
throw new Exception("xxx");

float[][] result = new float[aRows][];
for (int i = 0; i < aRows; ++i)
result[i] = new float[bCols];

for (int i = 0; i < aRows; ++i) // each row of A
for (int j = 0; j < bCols; ++j) // each col of B
for (int k = 0; k < aCols; ++k) // could use k < bRows
result[i][j] += a[i][k] * b[k][j];
return result;
}
```

And here’s a liitle demo:

```static void Main(string[] args)
{
float[][] A = ArrayToMatrix(new float[] { 1, 2, 3,
4, 5, 6 },
2, 3);  // 2x3
float[][] B = ArrayToMatrix(new float[] { 1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12},
3, 4);   // 3x4
float[][] AB = MatrixProduct(A, B);  // 2x4
Print(AB, 4);