Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime error in C++ with eigen library, any suggestions?

Tags:

c++

eigen

I am new to C++ and eigen library. I am trying to code some simple stuff, but do not know where I am going wrong. Here is my code:

#include<iostream>
#include<Eigen\Dense>
#include<cmath>
#include<fstream>

  using namespace std;
  using namespace Eigen;

  int main (int argc, char* argv[])
  {
      int n = 200;

      Matrix<double, Dynamic,1> u_n;
      u_n.setZero(n,1);

      Matrix<double, Dynamic,1> u_n_minus_one;
      u_n_minus_one.setZero(n,1);

      Matrix<double, Dynamic,1> u_n_plus_one;
      u_n_plus_one.setZero(n,1);

      std::ofstream fileWriter ("Values.txt");
      assert(fileWriter.is_open());

      float r=2;
      float F=100;

      for (int t=0;t<=5;t=t+1)
      {


                u_n_plus_one (0,0) =0;
//source of error
                u_n_plus_one.block(1,0,n-1,0) = pow(r,2)*( u_n.block(1,0,n-2,0)+ u_n.block(3,0,n,0)) + 2*(1-pow(r,2))*u_n.block(1,0,n-1,0)-u_n_minus_one.block(1,0,n-1,0);
//source of error
                u_n_plus_one (floor(n/2),0)=F;
                u_n_plus_one (n-1,0) =0 ;    //corrected from (n,0) to (n-1,0)


    u_n_minus_one = u_n ;
    u_n = u_n_plus_one ;

    //writing values to file
    if (remainder(t, 10) == 0)
    {
        fileWriter<<u_n.transpose()<<std::endl;
    }

   }

      fileWriter.close();
  }

I am trying to declare a few matrices (though they are vectors). Then I am doing operations on blocks of matrices, and finally writing the results to the file. I did not get any compile time error, but program crashes during run.

I tried debugging the code and the error seem to lie within //source of error statements. Can someone help me with this?

like image 464
user3705273 Avatar asked May 18 '26 07:05

user3705273


1 Answers

As the page on Block operations says, matrix.block(i,j,p,q) denotes the block with p rows and q columns starting at the (i,j) entry. I think that u_n.block(3,0,n,0) in the program is supposed to refer to the block starting at the (3,0) entry and ending at the (n,0) entry, but in fact it refers to the block starting at the (3,0) entry and of size (n,0). The block starting at the (3,0) entry and ending at the (n,0) entry is denoted by u_n.block(3,0,n-2,1) or u_n.segment(3,n-2) or u_n.tail(n-2); see the link mentioned at the start.

like image 120
Jitse Niesen Avatar answered May 19 '26 20:05

Jitse Niesen