MATLAB: I am trying to convert this for loop from matlab to C. Could someone please help

for loopmatlab to csine functions in c

% variables
Fs = 2000; % Sampling frequency
T = 1/Fs; % Sampling period
L = 4000; % Length of signal
t = (0:L-1)*T; %time samples
A=[16 18 28 33 38 41 59 43 40 58];% Amplitude of noise in dBA (refer to the measurements from consultant)
forigin=[25 31.5 40 50 63 80 100 125 160 200];% Frequency of the noise components (refer to the measurements from consultant)
S=zeros(1,length(t));% This will be the signal representing transformer noise, in your case, it will be the sound created from exciter
for k=1:length(A)
S = S+10^(A(k)/20)*sin(2*pi*forigin(k)*t);%Creating the transformer noise from the amplitude and frequency components, in your case, it will be the sound created from exciter
end
It is implementing the for loop to C.
I have implemented the variables and the "t" values so far.
Thanks any one who can help
Kay

Best Answer

Note: It's been ages since I've written any C code, and even then it was mostly C++ not C. Expect some bugs.
First you'll have to include the math library whatever that is on Arduino. Usually, it's math.h, so:
#define _USE_MATH_DEFINES // to force M_PI to exist
#include <math.h> //for pow, sin and M_PI
The main difficulty with the matlab code is that the operation on S is vectorised which is not an option in C, you have to convert that into a loop, hence you'll have a double for loop.
I would recommend that you name the size of the arrays either using a #define or a variable:
#define TSIZE 40 //or 4000
#define ASIZE 10 //for A and forigin
or
int TSIZE = 40;
int ASIZE = 10;
and use that for all your array declaration
double t[TSIZE];
double A[ASIZE] = {16 18 28 33 38 41 59 43 40 58}; //makes life easier if it's declared as double
double forigin[ASIZE] = {25.0 31.5 40.0 50.0 63.0 80.0 100.0 125.0 160.0 200.0};
//... code to fill t
On to the S calculation:
double S[TSIZE];
int i, k;
//initialise S to 0
for (i = 0; i < TSIZE; ++i) S[i] = 0;
//implement the for k=1:length(A)
for (k = 0; i < 10; ++i){
//devectorise the S calculation
for (i = 0; i < TSIZE; ++i){
S[i] = S[i] + pow(10, A[k]/20) * sin(2*M_PI*forigin[k]*t[i]);
}
}
edit: You could move the calculation of pow(10, A[k]/20) out of the i loop since it only depends on k.