## Fun with matrix multiplication and unsafe code 1

In this post I will compare two methods that perform matrix multiplication. We start by defining the Matrix class:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class Matrix { private readonly double[,] _matrix; public Matrix(int dim1, int dim2) { _matrix = new double[dim1, dim2]; } public int Height { get { return _matrix.GetLength(0); } } public int Width { get { return _matrix.GetLength(1); } } public double this[int x, int y] { get { return _matrix[x, y]; } set { _matrix[x, y] = value; } } } |

Next we add the first algorithm to the Matrix class which performs a naive multiplication:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public static Matrix NaiveMultiplication(Matrix m1, Matrix m2) { Matrix resultMatrix = new Matrix(m1.Height, m2.Width); for (int i = 0; i < resultMatrix.Height; i++) { for (int j = 0; j < resultMatrix.Width; j++) { resultMatrix[i, j] = 0; for (int k = 0; k < m1.Width; k++) { resultMatrix[i, j] += m1[i, k] * m2[k, j]; } } } return resultMatrix; } |

The second method uses unsafe code: (more…)