2011-09-16 20 views
0

は、私たちがこのような3×3行列があるとします。行列とベクトル乗算

1 3 4 
2 6 8 
9 0 12 

そして、このようないくつかのベクトル:

1 2 3 

私の質問は:私が増殖することができるようにそれを実装する方法互いに?

#include <cstdlib> 
#include <math.h> 
#include <iostream> 

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    int a[3][3]={{ 2,4,3},{1,5,7},{0,2,3}}; 
    int b[]={2,5,6}; 
    int c[3]; 

    for (int i=0;i<3;i++){ 
     c[i]=0; 
    } 

    for (int i=0;i<3;i++){ 
     for (int j=0;j<3;j++){ 
      c[i]+=(a[i][j]*b[j]); 
     } 
    } 

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

    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

私が得た結果は次のとおりです:

0x22ff10 
0x22ff1c 
0x22ff28 
+1

このような配列は印刷できません。各要素を個別に印刷するには、ループを作成する必要があります。 – Mysticial

答えて

4

変更:

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

に:

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

はい、私は正確にタイプミスしました。 –

3

私はあなたが印刷になりたいと思う私は、サンプルコードを持っていますc[i]a[i] 、あなたの最後のループで。

2

オブジェクトをデザインしますか?

// matrix of ints, floats, doubles, whatever numeric type you want 
template<typename T> 
class Matrix 
{ 
public: 
    Matrix(int rows, int cols) 
    { 
     // init m_values to appropriate rows and cols 
    } 

    Matrix<T> operator+(const Matrix<T>& rhs) 
    { 
     // add this matrix to the rhs matrix 
    } 

    Matrix<T> operator*(const Matrix<T>& rhs) 
    { 
     // verify both matrices have same dimensions (3x3 etc) 
     // multiple this matrix by rhs by indexing into m_values 
    } 

    // etc 

private: 
    // two dimensional dynamic array of type T values 
    std::vector<std::vector<T>> m_values; 
}; 

操作を実行するためにメンバー以外のテンプレート機能を使用することもできます。あなたはそれが空想的であるようにしたい場合は、値、等価、行操作などを持つを表すクラスを作成します。次に、行のベクトルに関してMatrixクラスを作成します。