Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a vector from a two dimensional array efficiently in C#

I have a very large two dimensional array and I need to compute vector operations on this array. NTerms and NDocs are both very large integers.

var myMat = new double[NTerms, NDocs];

I need to to extract vector columns from this matrix. Currently, I'm using for loops.

            col = 100;
            for (int i = 0; i < NTerms; i++)
            {
                myVec[i] = myMat[i, col];
            }

This operation is very slow. In Matlab I can extract the vector without the need for iteration, like so:

myVec = myMat[:,col];

Is there any way to do this in C#?

like image 757
Leeor Avatar asked Feb 11 '13 15:02

Leeor


1 Answers

There are no such constructs in C# that will allow you to work with arrays as in Matlab. With the code you already have you can speed up process of vector creation using Task Parallel Library that was introduced in .NET Framework 4.0.

Parallel.For(0, NTerms, i => myVec[i] = myMat[i, col]);

If your CPU has more than one core then you will get some improvement in performance otherwise there will be no effect.

For more examples of how Task Parallel Library could be used with matrixes and arrays you can reffer to the MSDN article Matrix Decomposition.

But I doubt that C# is a good choice when it comes to some serious math calculations.

like image 147
Alexander Manekovskiy Avatar answered Sep 24 '22 15:09

Alexander Manekovskiy