How to create a Fourier series using for loops

조회 수: 11 (최근 30일)
Ross King
Ross King 2022년 10월 2일
댓글: Torsten 2022년 10월 2일
I am supposed to plot this function on matlab along with another function. I have tried using for loops to create this, I am new to matlab and I don't know what I am doing wrong. Could someone point me in the right direction please? the range for x is from -2 to 2 and NUM is 14
f_init = repelem(0.5,401)
f_approx = (2/((k^2)*(pi^k)))*((-1^k)-1)*cos(k*((pi*x)/2))+(2/(pi*k))*(-1^(k+1))*sin(k*(pi*x/2));
t= length(x)
for k=1:14
for x=-2:0.01:2
F(x) = f_init(t)+ f_approx(k);
end
end
plot(F);

채택된 답변

Torsten
Torsten 2022년 10월 2일
편집: Torsten 2022년 10월 2일
k = 1:14;
x = (-2:0.01:2).';
f = 0.5 + sum(2./(k.^2*pi^2).*((-1).^k-1).*cos(pi*k.*x/2) + 2./(k*pi).*(-1).^(k+1).*sin(pi*k.*x/2),2);
plot(x,f)
f is a (401x14) matrix with row i made up of the k terms of the Fourier series, evaluated at x(i).
  댓글 수: 3
Ross King
Ross King 2022년 10월 2일
what does the " . ' " part do? So there are k rows in the f matrix and you add all the terms in the x(ith) column together? What does the dot after the k do in the sum part of your function? I am confused about the why you've put periods in your function.
Torsten
Torsten 2022년 10월 2일
.^, ./ and .* are elementwise operations for vectors and matrices being potentiated, divided or multiplied.
This is in contrast to matrix operations.
Look what comes out if you try
a = [1 2 3];
b = [4 5 6];
a.^b
ans = 1×3
1 32 729
a./b
ans = 1×3
0.2500 0.4000 0.5000
a.*b
ans = 1×3
4 10 18
or
(a.').^b
ans = 3×3
1 1 1 16 32 64 81 243 729
(a.')./b
ans = 3×3
0.2500 0.2000 0.1667 0.5000 0.4000 0.3333 0.7500 0.6000 0.5000
(a.').*b
ans = 3×3
4 5 6 8 10 12 12 15 18
For further information, see

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

추가 답변 (0개)

카테고리

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