4

I want to calculate something like: Matrix<float> * Matrix<double>

the Matrix<float> has about 6M*3 elements , how can I convert the Matrix<double> to Matrix<float> so that I can get a Matrix<float> result.

TylerH
  • 20,799
  • 66
  • 75
  • 101
xcl
  • 45
  • 4
  • 2
    How big is "very big", and is created a copy of the original `Matrix` (but using `double` values) prohibitively slow/memory-hungry? (If you haven't at last tried that, that seems like the simplest option...) – Jon Skeet May 12 '15 at 15:28
  • And why can't the result Matrix be a Matrix? – Dzyann May 12 '15 at 15:39
  • this matrix have around 6M * 3 elements – xcl May 12 '15 at 16:06

2 Answers2

3

You can convert your double matrix argument to a float matrix using the Map function:

Matrix<double> m1 = Matrix<double>.Build.Random(6000000,3);
Matrix<float> m2 = m1.Map(x => (float)x);

Or alternatively

Matrix<float> m2 = m1.Map(Convert.ToSingle);
Christoph Rüegg
  • 4,626
  • 1
  • 20
  • 34
1

Here's how to convert an array of double to an array of float, then you just need to convert your matrix to array and vice versa

public static float[][] Convert(double[][] mtx)
{
    var floatMtx = new float[mtx.Length][];
    for (int i = 0; i < mtx.Length; i++)
    {
        floatMtx[i] = new float[mtx[i].Length];
        for (int j = 0; j < mtx[i].Length; j++)
            floatMtx[i][j] = (float)mtx[i][j];
    }
    return floatMtx;
}
Or:

public static float[][] Convert(double[][] mtx)
{
    return mtx.Select(i => i.Select(j => (float)j).ToArray()).ToArray();
}
MRebai
  • 5,344
  • 3
  • 33
  • 52