This is my function returning matrices from Matlab. This code run very slowly.
I was trying to use Parallel.For
in-order to run it in parallel threads but I got different results than running it on one thread.
Am I iterating the matrix in a wrong order? Row, col vs col, row? Can you please review this code any suggest some performance boost tips?
public static SerializableMatrix ParseNumericMatrix(MWNumericArray matrix)
{
SerializableMatrix resultMatrix;
int[] dimensions = matrix.Dimensions;
if (dimensions.Length > 3 || dimensions.Length < 2)
{
throw new ArgumentException("Input matrix dimensions are too long", "Three is the max dimensions");
}
var height = dimensions[0];
var width = dimensions[1];
resultMatrix = new SerializableMatrix() { Width = width, Height = height, Data = new List<double[]>() };
if (dimensions.Length == 2)
{
var dataArray = new double[width * height];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
dataArray[i * width + j] = (double)matrix[i, j];
}
}
resultMatrix.Data.Add(dataArray);
return resultMatrix;
}
if (dimensions.Length == 3)
{
int depth = dimensions[2];
for (int depthIndex = 0; depthIndex < depth; depthIndex++)
{
var dataArray = new double[width * height];
for (int i = 0; i < height; i++)
{
for (int j = 0; j < width; j++)
{
// matlab indices start at 1 , not 0!!!
dataArray[i * width + j] = (double)matrix[i + 1, j + 1, depthIndex + 1];
}
}
resultMatrix.Data.Add(dataArray);
}
}
return resultMatrix;
}