Nested for loop fourier series
3 views (last 30 days)
Show older comments
I'm trying to use a nested for loop to do a fourier series. I have to evaluate n to 10 then use the new n for each pass to analyze t. n=10 t=10 I'm not quite sure how to do the nested for loop section. Any help is highly appreciated
This is what I have so far
y = [1.0668 1.8288 2.7432 3.5662 4:2977 4.6634 2.5908 2.3165 2.6518 3.0785 3.3223 ... 2.6213 0.3200 - 0.5791 - 1.0668 - 1.4326 - 1.4630 - 1.1887 - 0.5182 0.1524 1.0668];
n=10
T=2*pi %Period
O=2*pi/T %omega
t=linspace(0,2*pi,length(y))
a0=1/2*pi*trapz(t,y)
an(i)=(2/T)*trapz(t,y.*cos((n(i)*O.*t))) %finds an for i=n
bn(i)=(2/T)*trapz(t,y.*sin((n(i)*O.*t))) %finds bn for i=n
for i=1:n
for j=1:length(y)
n(i)=i
an1(j)=(2/T)*trapz(t,y.*cos((n(i)*O.*t))) %finds an1 using each n and a different t each loop
bn1(j)=(2/T)*trapz(t,y.*sin((n(i)*O.*t))) %finds bn1 using each n and a different t each loop
end
end
M=a0+an1+bn1
0 Comments
Answers (1)
Andrei Bobrov
on 11 Jun 2014
Edited: Andrei Bobrov
on 11 Jun 2014
To = 2*pi;
s = numel(y);
t = linspace(0,To,s).';
n = 1:10;
ang = t*n;
a0_1 = 1/To*trapz(t,y);
abn_1 = 2/To*trapz(t,[bsxfun(@times,y,[cos(ang), sin(ang)]);
an_1 = abn_1(n);
bn_1 = abn_1(n(end)+n);
or with use fft
nn = numel(y);
x = fft(y(1:end-1));
a0_1 = x(1)/(nn-1);
abn_2 = 2/(nn-1)*x(2:end);
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!