How to resolve the algorithm Apply a digital filter (direct form II transposed) step by step in the C programming language
How to resolve the algorithm Apply a digital filter (direct form II transposed) step by step in the C programming language
Table of Contents
Problem Statement
Digital filters are used to apply a mathematical operation to a sampled signal. One of the common formulations is the "direct form II transposed" which can represent both infinite impulse response (IIR) and finite impulse response (FIR) filters, as well as being more numerically stable than other forms. [1] Filter a signal using an order 3 low-pass Butterworth filter. The coefficients for the filter are a=[1.00000000, -2.77555756e-16, 3.33333333e-01, -1.85037171e-17] and b = [0.16666667, 0.5, 0.5, 0.16666667] The signal that needs filtering is the following vector: [-0.917843918645, 0.141984778794, 1.20536903482, 0.190286794412, -0.662370894973, -1.00700480494, -0.404707073677 ,0.800482325044, 0.743500089861, 1.01090520172, 0.741527555207, 0.277841675195, 0.400833448236, -0.2085993586, -0.172842103641, -0.134316096293, 0.0259303398477, 0.490105989562, 0.549391221511, 0.9047198589] [Wikipedia on Butterworth filters]
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Apply a digital filter (direct form II transposed) step by step in the C programming language
The C code implements a program that reads a signal data file, processes it, and prints or saves the filtered signal to the output file. Here's a detailed explanation of the code:
-
Header Files:
- The code includes the necessary header files:
<stdlib.h>: for memory allocation and manipulation functions.<string.h>: for string manipulation functions.<stdio.h>: for input and output operations.
- The code includes the necessary header files:
-
Constants and Data Structures:
MAX_LENis a constant that defines the maximum length of strings used in the program.vectoris a user-defined data structure that represents a vector with afloat*pointer to its values and anintrepresenting its size.
-
Function
extractVector:- This function takes a character array
stras input and extracts a vector of floating-point values from the string. - It counts the number of space-separated tokens in the string to determine the size of the vector.
- It allocates memory for the vector's values and stores the floating-point values obtained from the tokens in the vector.
- It returns the extracted vector.
- This function takes a character array
-
Function
processSignalFile:- This function takes a file name
fileNameas input and processes a signal data file to perform filtering. - It opens the file and reads three lines:
- The first line contains the coefficients for the numerator polynomial.
- The second line contains the coefficients for the denominator polynomial.
- The third line contains the signal data.
- It extracts the coefficient vectors and the signal vector using the
extractVectorfunction. - It allocates memory for the filtered signal vector.
- It applies the IIR (Infinite Impulse Response) filtering algorithm on the signal vector using the coefficients.
- It returns the filtered signal vector.
- This function takes a file name
-
Function
printVector:- This function takes a vector
vand an optional output file nameoutputFileas input. - If
outputFileisNULL, it prints the vector values to the console. - Otherwise, it writes the vector values to the specified output file.
- This function takes a vector
-
mainFunction:- The
mainfunction is the entry point of the program. - It checks the number of command-line arguments.
- If there are not exactly two or three arguments, it prints an error message and exits.
- If there are three arguments, it allocates memory for a string to store the message "written to " concatenated with the output file name.
- It calls the
processSignalFilefunction to process the signal data file and obtain the filtered signal vector. - It calls the
printVectorfunction to print or save the filtered signal vector.
- The
The provided C code takes a signal data file as input and performs a filtering operation on the signal data to produce a filtered signal. Here's a detailed explanation of the code:
-
Header Files and Macros:
- The code includes essential header files like
<stdlib.h>,<string.h>, and<stdio.h>for standard C library functions and operations. - It defines a macro
MAX_LENwith a value of 1000, which represents the maximum length of strings used in the program.
- The code includes essential header files like
-
Structure Definition (
vector):- A custom
vectorstructure is defined usingtypedef. This structure contains two members:float* values;: A pointer to an array of floating-point numbers representing the vector's values.int size;: An integer representing the number of elements in the vector.
- A custom
-
Function
extractVector:- This function extracts a vector of floating-point numbers from a given character string (
char* str). - It calculates the number of values in the string based on the spaces encountered.
- It dynamically allocates memory for the vector's values array and initializes its size.
- It uses the
strtokfunction to tokenize the string, convert each token to a float, and store it in the values array. - Finally, it returns the extracted vector.
- This function extracts a vector of floating-point numbers from a given character string (
-
Function
processSignalFile:- This function processes the signal data file specified by
fileNameand performs filtering on the signal. - It reads three lines from the file:
- Line 1: Contains the first set of coefficients (
coeff1) for the filter. - Line 2: Contains the second set of coefficients (
coeff2) for the filter. - Line 3: Contains the signal data (
signal) to be filtered.
- Line 1: Contains the first set of coefficients (
- It calls the
extractVectorfunction to extract these vectors from the strings. - It creates a new vector
filteredSignalto store the filtered signal and initializes its values to zero. - It loops through each sample in the signal data and calculates the filtered value based on the coefficients and previous filtered values.
- Finally, it returns the
filteredSignalvector.
- This function processes the signal data file specified by
-
Function
printVector:- This function is used to print the contents of a vector to either the standard output (if
outputFileisNULL) or a file specified byoutputFile. - It iterates through the vector's values and prints them in a formatted manner.
- This function is used to print the contents of a vector to either the standard output (if
-
Main Function (
main):- The
mainfunction is the entry point of the program. - It accepts two or three command-line arguments:
argV[1]: The name of the signal data file.argV[2]: Optional output file name to save the filtered signal (if provided).
- It checks for the correct number of arguments and prints an error message if incorrect.
- If an output file is provided, it prints a message indicating where the results will be written.
- It calls the
processSignalFilefunction to process the signal data and obtain the filtered signal. - Finally, it calls the
printVectorfunction to print the filtered signal either to the standard output or the specified file.
- The
-
Usage:
- The program is designed to be run with a single input file containing signal data. An optional output file name can be provided to save the filtered signal.
- For example, to filter a signal data file named "signal.txt" and print the filtered signal to the standard output, you would run the program as follows:
./program signal.txt- If you want to save the filtered signal to a file named "filtered_signal.txt," you would use:
./program signal.txt filtered_signal.txt
Source code in the c programming language
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define MAX_LEN 1000
typedef struct{
float* values;
int size;
}vector;
vector extractVector(char* str){
vector coeff;
int i=0,count = 1;
char* token;
while(str[i]!=00){
if(str[i++]==' ')
count++;
}
coeff.values = (float*)malloc(count*sizeof(float));
coeff.size = count;
token = strtok(str," ");
i = 0;
while(token!=NULL){
coeff.values[i++] = atof(token);
token = strtok(NULL," ");
}
return coeff;
}
vector processSignalFile(char* fileName){
int i,j;
float sum;
char str[MAX_LEN];
vector coeff1,coeff2,signal,filteredSignal;
FILE* fp = fopen(fileName,"r");
fgets(str,MAX_LEN,fp);
coeff1 = extractVector(str);
fgets(str,MAX_LEN,fp);
coeff2 = extractVector(str);
fgets(str,MAX_LEN,fp);
signal = extractVector(str);
fclose(fp);
filteredSignal.values = (float*)calloc(signal.size,sizeof(float));
filteredSignal.size = signal.size;
for(i=0;i<signal.size;i++){
sum = 0;
for(j=0;j<coeff2.size;j++){
if(i-j>=0)
sum += coeff2.values[j]*signal.values[i-j];
}
for(j=0;j<coeff1.size;j++){
if(i-j>=0)
sum -= coeff1.values[j]*filteredSignal.values[i-j];
}
sum /= coeff1.values[0];
filteredSignal.values[i] = sum;
}
return filteredSignal;
}
void printVector(vector v, char* outputFile){
int i;
if(outputFile==NULL){
printf("[");
for(i=0;i<v.size;i++)
printf("%.12f, ",v.values[i]);
printf("\b\b]");
}
else{
FILE* fp = fopen(outputFile,"w");
for(i=0;i<v.size-1;i++)
fprintf(fp,"%.12f, ",v.values[i]);
fprintf(fp,"%.12f",v.values[i]);
fclose(fp);
}
}
int main(int argC,char* argV[])
{
char *str;
if(argC<2||argC>3)
printf("Usage : %s <name of signal data file and optional output file.>",argV[0]);
else{
if(argC!=2){
str = (char*)malloc((strlen(argV[2]) + strlen(str) + 1)*sizeof(char));
strcpy(str,"written to ");
}
printf("Filtered signal %s",(argC==2)?"is:\n":strcat(str,argV[2]));
printVector(processSignalFile(argV[1]),argV[2]);
}
return 0;
}
You may also check:How to resolve the algorithm Runge-Kutta method step by step in the C programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the C programming language
You may also check:How to resolve the algorithm Even or odd step by step in the C programming language
You may also check:How to resolve the algorithm EKG sequence convergence step by step in the C programming language
You may also check:How to resolve the algorithm String case step by step in the C programming language