简体   繁体   中英

OpenCV: fast matrix computation

I have an nxd matrix V=[v_1; v_2;...; v_n] V=[v_1; v_2;...; v_n] V=[v_1; v_2;...; v_n] ( ; means new row ) where v_i are 1xd vectors.

I want to compute the following sum: v_1^T*v_1 + v_2^T*v_2 + ... + v_n^T*v_n , which is a dxd matrix ( v_i^T is the transpose of v_i) .

For the moment I use a for loop, as in the code below, which is not efficient when n is very large (I think so).

#include <iostream>
#include <opencv2/core.hpp>
using namespace cv;
using namespace std;

int main (int argc, char * argv[])
{   
    int n=5, d=3;

    Mat V = Mat(n, d, CV_32F);
    randu(V, Scalar::all(0), Scalar::all(10));        
    cout<<V<<endl<<endl;

    Mat M = Mat::zeros(d, d, CV_32F);
    for(int i=0; i<n; i++)
    {
        M = M + V.row(i).t()*V.row(i);
    }

    cout<<M<<endl<<endl;    
    return 0;
}

Hope that somebody can suggest a faster way. Thanks in advance.

You can just take Vt()*V

(It took me a minute to realize it too, but if you go through the matrix multiplication you'll see it's the same)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM