user7465838
user7465838

Reputation:

Does Eigen Library in C++ have a dynamic vector or matrix

Is there a way to set a dynamic vector or matrix in Eigen library? If not, is there a way to still use the Eigen library in conjunction with another class like vector?

For example let's say I have n*1 matrix called MatrixXd S(n,1); Now for simplicity let n=3 and S = 4 2 6. Pretend that the elements in S are future stock prices and let K = 2 which will be the strike price. Don't worry you won't need to understand the terminology of an option. Now say I want to know at what positions of S will we have S - K > 0 and say I want to store these positions in a vector call b.

Clearly, depending on the elements of S the vector b will be of a different size. Thus, I need to have b being of a dynamic variable. The only class I am familiar with that allows this is the vector class i.e., #include <vector>.

My question is as follows: Is it okay to use the Eigen library and the #include <vector> class together? Note that I will be performing operations of b with the Eigen library vectors and matrices I have created.

If I am not making sense, or if my question is unclear please let me know and I will clarify as much as possible.

Upvotes: 0

Views: 1567

Answers (1)

luk32
luk32

Reputation: 16080

Yes, it does. It's presented in the "A simple first program" of Getting started:

#include <iostream>
#include <Eigen/Dense>
using Eigen::MatrixXd;
int main()
{
  MatrixXd m(2,2);
  m(0,0) = 3;
  m(1,0) = 2.5;
  m(0,1) = -1;
  m(1,1) = m(1,0) + m(0,1);
  std::cout << m << std::endl;
}

You do need to pass the size to the constructor, but it's works like a vector. You can resize it later on too.

MatrixXd is a convenient typedef to a Matrix template which uses Dynamic as a template value for Rows, and Cols. It's basically Matrix<double, Dynamic, Dynamic>.

So you can have not only dynamic sized vectors and matrices, but also arbitrarily large fixed-size ones. Eigen does pretty nifty optimizations for small matrices, so using a fixed size there might be beneficial.

Upvotes: 1

Related Questions