Nested for loop fourier series

조회 수: 6 (최근 30일)
Carlos So
Carlos So 2014년 6월 11일
댓글: Carlos So 2014년 6월 11일
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

답변 (1개)

Andrei Bobrov
Andrei Bobrov 2014년 6월 11일
편집: Andrei Bobrov 2014년 6월 11일
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);
  댓글 수: 1
Carlos So
Carlos So 2014년 6월 11일
Sorry, but it has to be done using a nested for loop.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by