farzin parsa
farzin parsa

Reputation: 547

Convert each row of matrix( float) in to a vector

I have a float[n,128] array. Now I want to convert each row into a separate vector as following:

// The code here is a Pseudo Code

int n=48;  
    float[,] arrFloat=new float[n,128];  
    VectorOfFloat v1 = new VectorOfFloat(128);  // Vn equals to number of n

     v1= arrFloat[0];
     v2=arrFloat[1]
      .
      .
      .
      .
      Vn

What is the optimize way?


I could possibly write the code as following, but I think there should be a better way:

 List<VectorOfFloat> descriptorVec = new List<VectorOfFloat>();
VectorOfFloat v1 = new VectorOfFloat();  
                    var temp = new float[128];  
                    for (int i = 0; i < descriptors1.GetLength(0); i++)  
                    {  
                        for (int j = 0; j < descriptors1.GetLength(1); j++)  
                        {  
                            temp[j] = descriptors1[0, j];  
                        }  
                        v1.Push(temp);  
                        descriptorVec.Add(v1);  
                    }  

Upvotes: 4

Views: 1971

Answers (1)

user629926
user629926

Reputation: 1940

You can use Buffer.BlockCopy or ArrayCopy instead of manually assigning each value in for

        static float[][] ToVectors(float[,] matrix)
    {

        var array = new float[matrix.GetLength(0)][];

        for (int i = 0; i < array.Length; i++)
        {
            array[i]=new float[matrix.GetLength(1)];
            Buffer.BlockCopy(matrix, i * matrix.GetLength(1), array[i], 0, matrix.GetLength(1) * sizeof(float));
        }


        return array;

    }

Upvotes: 3

Related Questions