简体   繁体   中英

Taking Keyboards inputs for matrix type variables in armadillo C++

I am not able to take keyboard inputs to set the values for vector or matrix type variables defined with the armadillo library. This is the code I am using.

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

I get the following error message

"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}')"

Attempts to input values one by one using cin>>mu1(i). I have also tried to take input as an array and then assign the elements to mu1.

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

This gave an error in the output window

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

I have had similar issue whenever I tried an assignment that involves submatrix on the left hand side. For eg:

B.row(1)=A

I would like to know if its possible to assign values to matrix/vector types from keyboard. Also, is there anyway to set values to a submatrix of a mat type using a simple assignment.

Vectors and matrices in Armadillo generally need to have a non-zero size before you can put elements into them. You can set the size during the construction of the matrix, or using .set_size() , or using .zeros() .

Change your code to:

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

Note that using cin is generally bad from a user interface point of view. Instead, you may want to store all the matrix or vector values in a text file, and then load the text file. For example, let's say we have a text file called A.txt , containing:

0.0  1.0  2.0  3.0
4.0  5.0  6.0  7.0

You can then load the file in Armadillo using:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM