2017-05-29 40 views
-2

我一直在嘗試使用C++的齊次轉換,但我不能讓矩陣乘法工作。我在代碼中做錯了什麼?不能有矩陣乘法工作正常

我檢查做手工和它似乎是錯誤的。我錯過了什麼?

#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; 

} 
+0

請花一些時間閱讀[如何調試小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 –

+0

您期望得到什麼結果,爲什麼,以及得到了什麼結果,如果您認爲矩陣乘法是問題,那麼爲什麼不將它隔離到一個不進行矩陣乘法的函數中? – Beta

+0

你的矩陣乘法工作正常......但你不能從函數返回cpp中的3個值。 – Chandini

回答

0

您正在用C++編寫python代碼。

def transform(): 
    return (6, 7, 8) 

x, y, z = transform() 
print (x, y, z) 

圓括號在python中創建一個複合類型(元組)的實例。輸出將是6,7,8,因爲它返回一個結果,但結果是三部分元組,並且x,y,z =(6,7,8)的賦值將元組的每個部分分配給不同的變量,因爲python如何分配一個元組。

實際發生在C++什麼當你寫(6,7,8)是逗號運算符,其評估的第一項和丟棄結果。 https://en.wikipedia.org/wiki/Comma_operator圓括號只是組操作員,在這裏沒有任何作用。因爲評估像「x」這樣的單個浮點值沒有副作用,所以它不會做任何事情,並且C++代碼中的「return(x,y,z)」與僅寫入「return z」相同。

因爲代碼是C++,所以你需要做與Python代碼實際做的一樣的事情(用三部分返回一個值),但是你需要用C++來完成,所以繼續並聲明一個類型。這是主要區別之一 - 你必須告訴編譯器類型是什麼。當然有很多方法可以做到,但是你不能只使用python語法。

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; 
+0

謝謝!它像一個魅力。 –