[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

Example 6: A Differentiator

The program below inverts and differentiates the signals read by getvec and writes the results with putvec. The output is readable as record ‘dif’. A wide variety of simple digital filters can be modelled on this example; see section Example 7: A General-Purpose FIR Filter, for a more general approach.

 
 1  #include <stdio.h>
 2  #include <wfdb/wfdb.h>
 3
 4  main(argc, argv)
 5  int argc;
 6  char *argv[];
 7  {
 8      WFDB_Siginfo *s;
 9      int i, nsig, nsamp=1000;
10      WFDB_Sample *vin, *vout;
11
12      if (argc < 2) {
13          fprintf(stderr, "usage: %s record\n", argv[0]); exit(1);
14      }
15      if ((nsig = isigopen(argv[1], NULL, 0)) <= 0) exit(2);
16      s = (WFDB_Siginfo *)malloc(nsig * sizeof(WFDB_Siginfo));
17      vin = (WFDB_Sample *)malloc(nsig * sizeof(WFDB_Sample));
18      vout = (WFDB_Sample *)malloc(nsig * sizeof(WFDB_Sample));
19      if (s == NULL || vin == NULL || vout == NULL) {
20          fprintf(stderr, "insufficient memory\n");
21          exit(3);
22      }
23      if (isigopen(argv[1], s, nsig) != nsig) exit(2);
24      if (osigopen("8l", s, nsig) <= 0) exit(3);
25      while (nsamp-- > 0 && getvec(vin) > 0) {
26          for (i = 0; i < nsig; i++)
27              vout[i] -= vin[i];
28          if (putvec(vout) < 0) break;
29          for (i = 0; i < nsig; i++)
30              vout[i] = vin[i];
31      }
32      (void)newheader("dif");
33      wfdbquit();
34      exit(0);
35  }

(See http://physionet.org/physiotools/wfdb/examples/example6.c for a copy of this program.)

Notes:

Line 24:

Here we attempt to open as many output signals as there are input signals; if we cannot do so, the program exits after osigopen prints an error message.

Line 25:

The main loop of the program begins here. If 1000 samples can be read from each signal, the loop will end normally; if getvec fails before 1000 samples have been read, the loop ends prematurely.

Lines 26–27:

For each signal, we compute the negated first difference by subtracting the new sample from the previous sample.

Line 28:

One sample of each output signal is written here.

Lines 29–30:

The new input samples are copied into the output sample vector in preparation for the next iteration.

Line 32:

This step is optional. It creates a header file for a new record to be called ‘dif’, which we can then open with another program if we want to read the signals that this program has written. Since the record argument for osigopen was ‘8l’, we can also read these files using record ‘8l’; one reason for making a new ‘hea’ file here is that the ‘hea’ file for ‘8l’ may not necessarily indicate the proper sampling frequency for these signals.

Line 33:

Since the program writes output signals, it must invoke wfdbquit to close the files properly.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]

PhysioNet (wfdb@physionet.org)