1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
//solves the initial value problem using forward Euler method and outputs the results
double* System::ForwardEulerOdeSolve(double tau, double t_0, double t_e) {
//calculate the number of time steps
int n=floor((t_e-t_0)/tau)+1;
int sv_n=v_0.n_elem;//the number of state variables in the equations
int sd=sv_n+1;//number of all variables including time
//initialize output matrix
//first row contains time, the rest of the rows contain the evolution of state variables wrt to time
//-----------------------------------
double *pM(NULL);
pM=new double[n*sd];
mat OUT(pM, n, sd, true);
//-----------------------------------
//fill in the initial conditions
OUT(0,0)=t_0;
OUT(0,span(1, sv_n))=trans(v_0);
//create a column and a row vector used as temporary vectors in the calculation process
vec v_temp=v_0;
rowvec rs_temp=zeros<mat>(1,sv_n);
//create the respective pointer row and column vectors for quick transition
rowvec r_temp=rowvec(v_temp.memptr(), sv_n, false, false);
vec vs_temp=vec(rs_temp.memptr(), sv_n, false, false);
//iterate to get the complete solution
for (int i=1; i<n; i++) {
OUT(i,0)=OUT(i-1,0)+tau;//next time step
rs_temp=OUT(i-1,span(1,sv_n));//row vector with previous state
v_temp=ForwardEulerOde(tau,vs_temp);//column vector with current state
OUT(i,span(1, sv_n))=r_temp;//add current state to the output matrix
}
return pM;
}
|