Indexing Output Correctly

I wrote a code to solve the 1D diffusion equation using the Crank Nicholson method. However, when I try to output my solution values they continually overwrite the previous ones, so I only get values at the last time step. How can I fix this problem (my code is below)? Thanks


#include"nr3.h"
#include"tridag.h"
#include<stdio.h>

using namespace std;

void DX2(VecDoub &dVOut, VecDoub dVIn, double dLBC, double dRBC, double dCNGamma);

int main()
{
//constants
const double dLength=1.0;
const double dMaxTime=1.0;
const double dAlpha=1.0;
const double dLBC=1.0;
const double dRBC=0.0;
const int iNX=101; //# of FD points
const int iNT=101; //# of time steps

//derived constants
int iNP=iNX-2;
double dDX = dLength/(double)(iNX-1);
double dDT = dMaxTime/(double)(iNT-1);
double dDiffusionNumber = dAlpha*dDT/pow(dDX,2.0);
double dCNGamma =0.5*dDiffusionNumber;

//create storage
VecDoub dVSub(iNP,-dCNGamma),
dVDiag(iNP,1.0+2.0*dCNGamma),
dVSupd(iNP,-dCNGamma),
dVSol(iNP,0.0), //IC!
dVRHS(iNP,0.0);

//time loop
for (int t=0; t<iNT; t++)
{DX2(dVRHS,dVSol,dLBC,dRBC,dCNGamma);
tridag(dVSub,dVDiag,dVSupd,dVRHS,dVSol);
char case1out[]="1ddiffoutput.csv";
ofstream outfile(case1out,ios::app);
// outfile <<double(0.0*dLength)<<","<<double(dLBC)<<'\n';
// outfile <<double(1.0*dLength)<<","<<double(dRBC)<<'\n';

for(int i=0; i<iNP; i++)
for(int j=0; j<iNT; j++)
outfile<<double(i+1)*dDX<<","<<double(j+1)*dDT<<","<<dVSol[i,j]<<'\n';
outfile.close();
}
system("pause");
}


void DX2(VecDoub &dVOut, VecDoub dVIn, double dLBC, double dRBC, double dCNGamma)
{
//left point
dVOut[0]=2.0*dCNGamma*dLBC+(1.0-2.0*dCNGamma)*dVIn[0]+dCNGamma*dVIn[1];

//interior point
for(int i=1; i<dVIn.size()-1;i++)
{
dVOut[i]=dCNGamma*dVIn[i-1]+(1.0-2.0*dCNGamma)*dVIn[i]+dCNGamma*dVIn[i+1];
}

//right point
dVOut[dVOut.size()-1]=dCNGamma*dVIn[dVOut.size()-2]+(1.0-2.0*dCNGamma)*dVIn[dVOut.size()-1]+2.0*dCNGamma*dRBC;
}
Move the

ofstream outfile( case1out, ios::app );

line outside of the for loop.
I ammended that part of the code to look like:
//time loop
for (int t=0; t<iNT; t++)
{DX2(dVRHS,dVSol,dLBC,dRBC,dCNGamma);
tridag(dVSub,dVDiag,dVSupd,dVRHS,dVSol);}
char case1out[]="1ddiffoutput.csv";
ofstream outfile(case1out,ios::app);
for (int i=0; i<iNP; i++)
for (int j=0; j<iNT; j++)
outfile<<double(i+1)*dDX<<","<<double(j+1)*dDT<<","<<dVSol[i,j]<<'\n';
outfile.close();

I got an error moving only ofstream outfile(case1out,ios::app); out of the for loop, so I had to move char case1out[]="1ddiffoutput.csv"; out as well. I still have the same problem with the output file in that only the values from the last time step print.
Topic archived. No new replies allowed.