2D matrix multiplication in 2D matrix error

asked 2015-04-03 04:52:27 -0600

Gilad Darmon gravatar image

updated 2015-04-04 06:04:23 -0600

UPDATE I have a found a solution to my problem I need to work with CV_64F / double and everything is working fine.

My input are two double vectors I want to create b = (X'*X)^-1*X'*y = inv(X'*X)*X'*y*

the original matlab code is :

function c = linear_mapping(x0, y0)
    % Reshape input values just to make sure they are column order
    x0 = x0(:); % column wise order
    y0 = y0(:); % column wise order

    % Linear mapping y = X*b, where X = [1, x] and b are coefficients
    % Solving b = (X'*X)^-1*X'*y = inv(X'*X)*X'*y
    X = [ones(size(x0)), x0];
    b = linsolve(X, y0);
    c(1) = b(2);
    c(2) = b(1);
end

i'll update my code which is now creating the matrices i want the multiplication is different from matlab's result matlab's version :

X =

1.0e+03 *

0.0010    1.0743
0.0010    1.0740

X'

ans =

1.0e+03 *

0.0010    0.0010
1.0743    1.0740

X'*X

ans =

1.0e+06 *

0.0000    0.0021
0.0021    2.3075

inv(X'*X)

25402233.6743484    -23649.3170474466
-23649.3170474466   22.0173633149477

my new openCV version

CentroidXY Utilities::LinearMapping(std::vector<double> x0, std::vector<double> y0)
{       
    cv::Mat X = cv::Mat::ones(x0.size(),2, CV_32F);
    for (int i = 0; i < x0.size(); i++)
    {
        X.at<float>(i,1) = x0[i];
    }       
    cv::Mat XTrans;

    cv::transpose(X,XTrans);
    cv::Mat invMat;
    /*% Solving b = (X'*X)^-1*X'*y = inv(X'*X)*X'*y*/

    cv::Mat b = XTrans *X; 
    invMat  =b.inv();   
}

here is my output:

 X: 
[1, 1074.272;
  1, 1073.9705]

 X': 
[1, 1;
  1074.272, 1073.9705]

 X'*X 
[2, 2148.2424;
  2148.2424, 2307472.8]

 inv(X'*X)
[-51162084, 47631.574;
  47631.574, -44.344692]

once again what is the difference?

edit retag flag offensive close merge delete

Comments

what you're doing wrong is not telling us the details of the crash, any exceptions, error messages, stack trace...

boaz001 gravatar imageboaz001 ( 2015-04-03 06:45:27 -0600 )edit

@boaz001 Thanks for the comment. I have added the exception

Gilad Darmon gravatar imageGilad Darmon ( 2015-04-03 06:53:34 -0600 )edit

I think XTrans and X are not of the same type and size.

boaz001 gravatar imageboaz001 ( 2015-04-03 07:08:23 -0600 )edit

since XTrans stems from X it has the same type and appropriate size. Maybe mul doesn't work with multiple channels.

Guanta gravatar imageGuanta ( 2015-04-03 13:08:27 -0600 )edit

OK I have updated the solution to my problem thanks all

Gilad Darmon gravatar imageGilad Darmon ( 2015-04-04 06:22:58 -0600 )edit