2011-09-16 252 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類。