So right now I am simply trying to take a dummy data file,
1.30640 1
0.91751 1
0.49312 1
0.49312 0
1.79859 1
1.86360 1
0.12313 1
0.12313 0
-0.19091 1
1.82377 1
0.63205 1
0.63205 0
1.23357 1
0.62110 1
0.80438 1
and at the moment store it as a gal_matrix for manipulations later. Below is code which simply at the moment, given a data file name finds out how long it is (i.e. number of rows), initializes a gsl_matrix struct and then try to scan the text file into that matrix, called chain.
#include <stdio.h> // Needed for printf() and feof()
#include <math.h> // Needed for pow().
#include <stdlib.h> // Needed for exit() and atof()
#include <string.h> // Needed for strcmp()
#include <gsl/gsl_matrix.h> // Needed for matrix manipulations
/*------------ Defines -----------------------------------------------------------------*/
#define MAX_SIZE 10000000 // Maximum size of the time series array
#define NUM_LAG 1000 // Number of lags to calculate for
/*
*----------------------------------------------------------------------------------------
* Main program
*----------------------------------------------------------------------------------------
*/
int main(int argc, char* argv[]) {
//--------Initialization--------------------------------------------------------------
double ac_value; // computed autocorrelation value
int i,j; // Loop counter
long int N;
double mean, variance;
gsl_matrix * chains;
char filename[100];
FILE* in_file; // input file
FILE* out_file; // output file
int no_params; // number of parameters to calculate autocorrelation for
int first_column; // Which column first corresponds to a chain
int ch; // to determine number of samples in file
printf("-------------------------------------------------------------------------\n");
//--------Check that there are the correct number of arguments passed-----------------
if(argc != 4) {
printf("usage: ./auto_corr chainfile no_params first_column \n");
exit(1); // 0 means success typically, non-zero indicates an error
}
//--------Extract arguments-----------------------------------------------------------
sprintf(filename,"%s",argv[1]); // convert input file to string
in_file = fopen(filename,"rb"); // open input file for reading
no_params = atoi(argv[2]);
first_column = atoi(argv[3]);
//--------What is the number of samples in chain file?--------------------------------
N = 0; // Initialize count
while(!feof(in_file)) {
ch = fgetc(in_file);
if(ch == '\n'){
N++;
}
}
printf("Number of samples: %li\n", N); // print number of samples
if (N > MAX_SIZE) { // throw error if there are too many samples
printf("ERROR - Too many samples! MAX_SIZE = %i", MAX_SIZE);
exit(2);
}
//--------Generate a gsl matrix from the chains---------------------------------------
printf("%i\n", no_params);
chains = gsl_matrix_alloc(N, no_params); // allocate memory for gsl_matrix(rows, cols)
// print the matrix (for testing)
printf("Chain matrix \n");
for (int m=0;m<N;m++) { //rows
for (int n=0; n<no_params;n++) { // columns
printf("%f ",gsl_matrix_get(chains,m,n));
}
printf("\n");
}
// gsl_matrix_fprintf(stdout,chains,"%f"); // easy way to print, no formatting though
gsl_matrix_fscanf(in_file, chains); // read in chains to the gsl_matrix
fclose(in_file);
The error is occurring in the gsl_matrix_fscanf line, and the output I am seeing is
$ ./auto_corr auto_corr_test_data.dat 2 0
-------------------------------------------------------------------------
Number of samples: 15
2
Chain matrix
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
0.000000 0.000000
gsl: ./fprintf_source.c:165: ERROR: fscanf failed
Default GSL error handler invoked.
Abort trap: 6
I forgot to rewind the input file after I determined the number of rows.
Related
I have the following code for calculating the Eigen Vectors (left and right) of a Stochastic matrix in C (with gcc compiler):
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
double A[6][6] = {{0.2,.200000,0.2000000,0.000000,0.200000,0.200000},
{0.200000,0.000000,0.000000,0.000000,0.000000,0.800000},
{0.200000,0.000000,0.000000,0.800000,0.000000,0.000000},
{0.200000,0.000000,0.400000,0.000000,0.400000,0.000000},
{0.200000,0.000000,0.000000,0.800000,0.000000,0.000000},
{0.200000,0.800000,0.000000,0.000000,0.000000,0.000000}};
int n=6;
char Lchar='V';
char Rchar='V';
double *eigReal=(double *)malloc(n*sizeof(double *));
double *eigImag=(double *)malloc(n*sizeof(double *));
double vl[6][6], vr[6][6];
int one=1, two=6;
int lwork=6*n;
double *work=(double *)malloc(lwork*sizeof(double *));
int info;
dgeev_(&Lchar,&Rchar,&n,A,&n,eigReal,eigImag,
vl,&two,vr,&two,
work,&lwork,&info);
for(int i=0; i<6; i++)
{
printf("\n");
for(int j=0; j<6; j++)
printf("%f ", vr[i][j]);
}
for(int i=0; i<6; i++)
{
printf("\n");
for(int j=0; j<6; j++)
printf("%f ", vr[i][j]);
}
return 0;
}
Then I print vr and vl to get the following matrices (none of which seems to be correct)
(the ordering of the rows and columns might be wrong i.e it might be the eigen vectors are actually transpose).
0.476331 0.476331 0.264628 0.423405 0.264628 0.476331
0.852803 -0.213201 0.000000 -0.426401 -0.000000 -0.213201
0.000000 0.000000 -0.408248 0.816497 -0.408248 0.000000
0.000000 -0.534522 0.267261 0.534522 0.267261 -0.534522
0.000000 -0.706706 -0.013739 0.027477 -0.013739 0.706706
0.550263 -0.137566 0.540215 -0.275132 -0.540215 -0.137566
0.408248 0.408248 0.408248 0.408248 0.408248 0.408248
0.686304 -0.171576 -0.608494 -0.171576 0.265343 -0.171576
0.243660 -0.051773 -0.578693 0.517778 -0.578693 -0.009142
0.000000 -0.447214 0.447214 0.447214 0.447214 -0.447214
0.000000 -0.707107 -0.000000 -0.000000 -0.000000 0.707107
0.000000 0.000000 0.707107 0.000000 -0.707107 0.000000
So where is the mistake in my code?
I'm honestly going nuts here trying to understand why this generic array printer implementation is not working. Well, it works for an array of int's, but not for double's. What am I missing here?
void array_printer(FILE* stream, void* data, size_t data_type_size, size_t nr_rows, size_t nr_cols, char *format){
size_t offset = 0;
for (size_t r=0; r<nr_rows;++r){
for (size_t c=0; c<nr_cols; ++c){
fprintf(stream,format, *((int8_t*)data + offset*data_type_size));
//fprintf(stream,format, *((char*)data + offset*data_type_size)); // same behaviour
offset++;
}
fprintf(stream,"\n");
}
}
void array_print_double_2D(FILE* stream, double* data, size_t nr_rows, size_t nr_cols){
array_printer(stream, data, sizeof(double), nr_rows, nr_cols, " %lf ");
}
void array_print_int_2D(FILE* stream, int* data, size_t nr_rows, size_t nr_cols){
array_printer(stream, data, sizeof(int), nr_rows, nr_cols, " %d ");
}
int main(){
double *data_double = calloc(12, sizeof(double));
data_double[0] = 1;
data_double[1] = 2;
data_double[2] = 3;
array_print_double_2D(stdout, data_double, 3, 4);
/*
0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000 what??
0.000000 0.000000 0.000000 0.000000
*/
int*data_int = calloc(12, sizeof(int));
data_int[0] = 1;
data_int[1] = 2;
data_int[2] = 3;
array_print_int_2D(stdout, data_int, 3, 4);
/*
1 2 3 0
0 0 0 0 correct
0 0 0 0
*/
Expression *(int8_t*)(data+...) will return int8_t which is not consistent with printf specifier " %lf ". This results in Undefined behavior.
The problem can be efficiently solved with macros that generate the printers.
#include <stdio.h>
#include <stdlib.h>
#define DEFINE_ARRAY_PRINT_2D(TYPE, FMT) \
void array_print_ ## TYPE ## _2D(FILE* stream, void* data, size_t nr_rows, size_t nr_cols) { \
size_t offset = 0; \
for (size_t r=0; r<nr_rows;++r){ \
for (size_t c=0; c<nr_cols; ++c){ \
fprintf(stream,FMT, ((TYPE*)data)[offset]); \
offset++; \
} \
fprintf(stream,"\n"); \
} \
}
// generate printers
DEFINE_ARRAY_PRINT_2D(int, " %d ")
DEFINE_ARRAY_PRINT_2D(double, " %lf ")
int main(){
double *data_double = calloc(12, sizeof(double));
data_double[0] = 1;
data_double[1] = 2;
data_double[2] = 3;
array_print_double_2D(stdout, data_double, 3, 4);
int *data_int = calloc(12, sizeof(int));
data_int[0] = 1;
data_int[1] = 2;
data_int[2] = 3;
array_print_int_2D(stdout, data_int, 3, 4);
return 0;
}
Produces output:
1.000000 2.000000 3.000000 0.000000
0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000
1 2 3 0
0 0 0 0
0 0 0 0
As expected.
You're casting the memory to int8_t* and dereferencing it, what were you expecting? I'd provide some sort of enumeration to distinguish between the typesand cast to the right one when needed.
I'm trying to read the information I printed to a .txt file from a separate program, and display it in this new program. Although when I run the program, it says the file cannot be found. I suspect its my code, and not the file location as I have double checked my hard code, here is what I have so far, if anyone could point me in the right direction that would be great!
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 21
typedef struct data_slice
{
int t; // -> Time
float tp; // -> Valve pressure
float tf; // -> Sodium flow
float tt; // -> Sodium temp in Celsius
} data_slice;
void printIt(data_slice * data);
int main()
{
float num;
FILE *fptr;
data_slice data[ARRAY_SIZE];
if ((fptr = fopen("/Users/captainrogers/Documents/output_data.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%f \n", &num);
printIt(data);
fclose(fptr);
return 0;
}
void printIt(data_slice * data)
{
// Find the indice holding the time value of -10
int indice = 0;
for (int i = 0; i < ARRAY_SIZE; ++i)
{
if (data[i].t == -10)
{
indice = i;
break;
}
}
// Print results to screen
for (int i = 0, temp = indice; i < ARRAY_SIZE; ++i)
{
printf("%i\t %f\t %f\t %f\n", data[temp].t, data[temp].tp, data[temp].tf, data[temp].tt);
temp = (temp + 1) % ARRAY_SIZE;
}
}
Data I'm trying to print from .txt:
-10 595.000000 15.000000 167.000000
-9 557.000000 17.000000 168.000000
-8 634.000000 17.000000 114.000000
-7 656.000000 10.000000 183.000000
-6 561.000000 13.000000 139.000000
-5 634.000000 17.000000 124.000000
-4 672.000000 19.000000 155.000000
-3 527.000000 14.000000 166.000000
-2 656.000000 11.000000 188.000000
-1 661.000000 18.000000 141.000000
0 689.000000 17.000000 146.000000
1 624.000000 11.000000 104.000000
2 504.000000 20.000000 120.000000
3 673.000000 18.000000 147.000000
4 511.000000 12.000000 114.000000
5 606.000000 14.000000 171.000000
6 601.000000 13.000000 159.000000
7 602.000000 11.000000 127.000000
8 684.000000 10.000000 194.000000
9 632.000000 16.000000 139.000000
10 651.000000 13.000000 168.000000
fptr = fopen("C://Users//captainrogers//Documents//output_data.txt","r"))
try this code if you are sure your document is in the right file.
fopen("/Users/captainrogers/Documents/output_data.txt","r")
If the file can't be found, double-check your path. Maybe first try with the full path including the drive letter.
fscanf(fptr,"%f \n", &num);
Always check the return-value of fscanf(). "%f \n" is probably not the format string you want.
printIt(data);
Main problem: you never read any data into data[].
I am trying to use qsort to sort an array of x-y coordinate structs pointers based on their y value, but q sort is not comparing the correct values. I am baffled at this point, can anyone see what I am doing wrong?
sort function:
23 int sortFunc(const void * firsti, const void * secondi){
24
25 const Coordinate* first = firsti;
26 const Coordinate* second = secondi;
27
28 printf("Comparing %f & %f\n", first->y, second->y);
29 if(first->y < second->y){ return 1;}
30 else if(first->y == second->y){ return 0; }
31 else{ return -1; }
32
33 }
print function:
13 void printArray(Coordinate * array[], int size){
14
15 int x;
16 for(x=0; x < size; x++){
17 printf("Point %i : %f | %f\n", x, array[x]->x, array[x]->y);
18 }
19
20 }
and calling
79 qsort(pointArray, count, sizeof(Coordinate*), sortFunc);
80 printArray(pointArray, count);
yields
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Comparing 0.000000 & 0.000000
Point 0 : 103.253334 | -12.472327
Point 1 : -3.283118 | -3.101071
Point 2 : 9.289474 | -0.459975
Point 3 : 14.029107 | -11.844076
Point 4 : -6.465595 | 14.704790
Point 5 : -5.764663 | 8.882765
any idea what's happening?
Your comparison function is written as if you have an array of Coordinate structs, not an array of pointers to Coordinate structs.
Since you have an array of pointers to Coordinate structs, the comparison function will receive pointers to pointers to Coordinate structs as parameters. For this reason your comparison function should look as follows
int sortFunc(const void * firsti, const void * secondi)
{
const Coordinate* const* first = firsti;
const Coordinate* const* second = secondi;
if((*first)->y < (*second)->y){ return 1;}
else if((*first)->y == (*second)->y){ return 0; }
else{ return -1; }
}
I have a text file with numbers: two numbers on each row, separated by a space. Each pair of numbers represents an (x, y) co-ordinate. I am trying to write this in C, because it's the language I know, but I am working in Visual Studio 2010. The code I have is as follows:
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#define MAXPOINTS 10
int _tmain(int argc, _TCHAR* argv[])
{
double points [MAXPOINTS];
int i;
for (i = 0; i < MAXPOINTS; i++) {
points[i] = 0.0;
}
FILE* pFile;
pFile = fopen ("points.txt","r");
if (pFile == NULL)
{
printf("Could not open file\n");
return 0;
}
rewind (pFile);
i = 0;
while (fscanf(pFile, "%f %f", &points[i], &points[i + 1]) == 2) {
printf("blah\n");
i = i + 2;
}
for (i = 0; i < MAXPOINTS; i++) {
printf("[%d] = %f\n", i, points[i]);
}
fclose (pFile);
return 0;
}
The output is:
blah
blah
blah
[0] = 0.000000
[1] = 0.000000
[2] = 0.000000
[3] = 0.000000
[4] = 0.000000
[5] = 0.000000
[6] = 0.000000
[7] = 0.000000
[8] = 0.000000
[9] = 0.000000
Where points.txt has three rows:
100 200
300 400
500 500
I can't figure out why the numbers aren't being read into the array.
Any ideas?
%f format requires pointer to float, and you give pointer to double.