Up to this point, I have been doing my work in Matlab and reluctantly, Labview. I am trying to learn C to write some fast data analysis programs. As practice, I am currently working on generating a noisy exponential, using a simple fitting algorithm to find the exponential constant and writing the results to a binary file. (I am reading the binary file with Matlab to check my results.)
Everything seems to work fine is I use array sizes of 10 or less. If I use an array size greater than 10, the first tens elements of the time array look fine, all other elements are gibberish.
Any suggestions about this particular problem, or any other suggestions on my code, would be helpful.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main()
{
int length;
length=200;
struct data
{
int time[length];
double sig[length];
double fit[length];
};
struct data sig1;
int i,zero_moment;
double tau, noise,first_moment, tau_measured;
unsigned int iseed = (unsigned int)time(NULL);
srand(iseed);
FILE *fp;
if((fp=fopen("C:\\Users\\Brian\\Desktop\\C Files\\test2\\test2_data.bin", "w")) == NULL)
{
printf("Cannot save file");
}
tau=2;
noise=0.001;
zero_moment=0;
first_moment=0;
for (i=0; i<length; i++)
{
sig1.time[i]=i;
sig1.sig[i]=exp(-i/tau)+noise*((rand() % 100)-50) ;
}
for (i=0; i<length; i++)
{
zero_moment=zero_moment+sig1.time[i];
first_moment=first_moment+sig1.time[i]*sig1.sig[i];
}
tau_measured=(double)zero_moment/(2*first_moment);
for (i=0; i<length; i++)
{
sig1.fit[i]=exp(-(double)i/tau_measured);
}
fwrite(sig1.time, sizeof(sig1.time[0]), sizeof(sig1.time)/sizeof(sig1.time[0]), fp);
fwrite(sig1.sig, sizeof(sig1.sig[0]), sizeof(sig1.sig)/sizeof(sig1.sig[0]), fp);
fwrite(sig1.fit, sizeof(sig1.fit[0]), sizeof(sig1.fit)/sizeof(sig1.fit[0]), fp);
fclose(fp);
return 0;
}