Runtime error in C ++ with native library, any suggestions?
I am new to C ++ and my own library. I am trying to code some simple things but dont 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 multiple matrices (although they are vectors). Then I do operations on the matrix blocks and finally write the results to a file. I didn't have any compile-time error, but during the run, the program worked.
I tried to debug the code and the error seems to lie in the // source of the error statements. Can anyone help me with this?
source to share
As shown on the Block Operations page , matrix.block(i,j,p,q)
denotes a block with columns p
and columns q
starting with (i,j)
. I think the u_n.block(3,0,n,0)
program is supposed to refer to a block starting at record (3,0) and ending at record ( n
, 0), but in fact it refers to a block starting at (3.0) and size ( n
, 0) ... A block that starts at entry (3,0) and ends at entry ( n
, 0) is denoted by u_n.block(3,0,n-2,1)
either u_n.segment(3,n-2)
or u_n.tail(n-2)
; see the link mentioned at the beginning.
source to share