2014-10-04 60 views
1

我無法採用鍵盤輸入來設置矢量或矩陣類型的變量與犰狳庫定義的值。這是我正在使用的代碼。在鍵盤輸入矩陣類型變量在犰狳C++

#include <iostream> 
#include "armadillo" 
using namespace arma; 
using namespace std; 
int main() 
{ 
    vec mu1; 
    cin>> mu1; 
    return 0; 
} 

我得到以下錯誤消息

"E:\cpp\hell\mvnsamp.cpp|18|error: no match for 'operator>>' (operand types are 'std::istream {aka std::basic_istream}' and 'arma::vec {aka arma::Col}')"

嘗試輸入值逐一使用CIN >> MU1(i)中。 我也嘗試將輸入作爲數組 ,然後將元素分配給mu1。

float arr[20]={}; 
for(int i=0;i<5;i++) 
{ 
    cin>> arr[i]; 
} 
mu1(0)=arr[0]; 

這我也有類似的問題,每當我試圖涉及在左側小矩陣分配輸出窗口

"error:Mat::operator():index out of bounds terminate called after throwing an instance of std:: logic error what(): Mat::operator(): index out of bounds".

給了一個錯誤。 對於如:

B.row(1)=A 

我想知道,如果它可以分配的值從鍵盤矩陣/矢量類型。另外,無論如何,使用簡單的賦值將值設置爲墊子類型的子矩陣。

回答

0

Armadillo中的矢量和矩陣通常需要有一個非零大小,然後才能將元素放入其中。您可以在矩陣的construction期間設置尺寸,或使用.set_size()或使用.zeros()

你的代碼更改爲:

int main() 
    { 
    vec mu1(10, fill::zeros); 

    for(int i=0; i<10; i++) 
    { 
    double tmp; 

    cin >> tmp; 

    mu1(i) = tmp; 
    } 

    mu1.print("mu1:"); 

    return 0; 
    } 

注意,使用cin一般是從一個用戶界面,點差。相反,您可能希望將所有的矩陣或向量值存儲在文本文件中,然後加載文本文件。例如,假設我們有一個名爲A.txt一個文本文件,其中包含:

0.0 1.0 2.0 3.0 
4.0 5.0 6.0 7.0 

然後,您可以使用加載在犰狳的文件:

mat A; 
A.load("A.txt");