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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With