Search code examples
c++matrixmultiplication

Cant have matrix multiplication work properly


I have been trying to use homogeneous transformations on C++ but i cant get the matrix multiplication to work. Am I doing something wrong in the code?

I checked doing it by hand and it doesnt seem to be wrong. Did i miss something?

#include "stdafx.h"
using namespace std;

float point[3][1];
float point_trans[3][1] = {0,0,0};
float rot[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
float d[3][1] = {0,0,0};
float x,y,z;

float transform (float x1, float y1, float z1)
{
    point[0][0] = x1; 
    point[1][0] = y1;
    point[2][0] = z1;

    for(int i=0; i<3; ++i)
    {
        for(int j=0; j<1; ++j)
        {
            for(int k=0; k<3; ++k)
            {
                point_trans[i][j]+=rot[i][k]*point[k][j];
            }
        }
    }

    x1 = point_trans[0][0] + d[0][0];
    y1 = point_trans[1][0] + d[1][0];
    z1 = point_trans[2][0] + d[2][0];

    return(x1,y1,z1);
}

int main()
{
    x = 6; y = 7; z = 8;

for(int i=0;i<3;i++)
{
    for(int j=0;j<3;j++)
    {
        cout << rot[i][j] << " ";
    }
    cout << endl;
}


    (x,y,z) = transform(x,y,z);
    cout << "X:" << x << " " << "Y:"<<y<<" "<<"Z:"<<z<<endl;
    system("pause");
    return 0;

}

Solution

  • You are writing python code in c++.

    def transform():
        return (6, 7, 8)
    
    x, y, z = transform()
    print (x, y, z)
    

    The parentheses create an instance of a composite type (tuple) in python. The output will be 6, 7, 8 because it returns one result, but that result is a three part tuple, and assignment of x, y, z = (6, 7, 8) assigns each part of the tuple to different variables because of how python does assignment with a tuple.

    What actually happens in c++ when you write (6, 7, 8) is the comma operator, which evaluates the first item and discards the result. https://en.wikipedia.org/wiki/Comma_operator The parentheses just group operators, and have no effect here. Because evaluating a single float value like "x" has no side effects, it doesn't do anything, and "return (x, y, z)" in c++ code is the same as just writing "return z".

    Because the code is c++ you need to do the same thing as what the python code actually did (return one value with three parts), but you need to do it in c++, so go ahead and declare a type. That's one of the key differences -- you have to tell the compiler what the types are. There are of course many ways to do it, but you can't just use python syntax.

    struct coordinate { float x, y, z; };
    
    coordinate transform(float x1, float y1, float z1)
    {
        // code
        return coordinate{ x1, y1, z1 };
    }
    
    // in main
    coordinate result = transform(x, y, z);
    cout << "X:" << result.x << " " << "Y:" << result.y << " " << "Z:" << result.z << endl;