フィルターのクリア

how can I plot the fourier series of this function by calculating the coeffcients and for different n?

1 回表示 (過去 30 日間)
I don't want to use loop in my code because the speed is low.this is my code but it doesn't work:
x = linspace(-2*pi, 2*pi, 1000);
a0 = 1/2;
n = 5;
an = zeros(1,n);
for i = 1:n
if mod(4,i)==1
an(1,i) = 2/i*pi;
elseif mod(4,i)==3
an(1,i) = -2/i*pi;
end
end
fs = zeros(1,n+1);
fs(1,1) = a0;
for i = 2:n+1
fs(1,i) = an(1,i)*sin(i*x);
end
plot(x,fs,'color','r');

採用された回答

Torsten
Torsten 2022 年 10 月 6 日
編集済み: Torsten 2022 年 10 月 6 日
Note that the function f you defined is even - thus it must be cos(n*x), not sin(n*x) that appears in the Fourier series.
x = linspace(-2*pi, 2*pi, 1000).';
a0 = 1/2;
n = 1000;
an = zeros(1,n);
for i = 1:n
if mod(i,4)==1
an(i) = 2/(i*pi);
elseif mod(i,4)==3
an(1,i) = -2/(i*pi);
end
end
f = a0 + sum(an.*cos((1:n).*x),2);
plot(x,f)

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2022 年 10 月 6 日
an = zeros(1,n);
i = 1 : n;
mask = mod(4,i) == 3;
an(1,mask) = -2./i(mask) * pi;
mask = mod(4,i) == 1;
an(1,mask) = +2./i(mask) * pi;
  2 件のコメント
Walter Roberson
Walter Roberson 2022 年 10 月 6 日
However:
n = 8;
i = 1 : n;
mod(4, i)
ans = 1×8
0 0 1 0 4 4 4 4
That is, the remainder when dividing 4 by 1 is 0, the remainder when dividing 4 by 2 is 0, the remainder when dividing 4 by 3 is 1, the remainder when dividing 4 by 4 is 0, the remainder when dividing 4 by 5 through 8 is 4...
Are you sure that is what you want to do?
Niloufar
Niloufar 2022 年 10 月 6 日
I wanted to calculate the coefficient of the fourier series but this code gives the wrong answer.an should be zero when n is even and for n=4k+1 should be 2/(n*pi) and for n=4k+3 should be -2/(n*pi) and after that I want to plot the fourier series until desired n. I mean use this formula for calculating the fourier series

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeLine Plots についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by