How to construct a Fourier series using a for loop?

3. Construct a Fourier series by using a for loop.
Hint: Be reminded from your work on Taylor series in Lab 1.
Note 1: Go with n until 17 instead of ∞.

6 Comments

Show us what you have tried
This is my code so far.
clear all; close all; clc;
incrm=0.01; T0=2; w0=pi;
t=0:0.01:10;
xt = ones(1,numel(t));
xt(t>=1 & t<2 | t>=3 & t<4 | t>=5 & t<=6 | t>=7 & t<=8 | t>=9 & t<=10)=0;
a0 = (1/T0) * trapz(t(1:1+T0/incrm), xt(1:1+T0/incrm), 2);
k=1:17;
for kk = 1 : size(k,2)
ak(kk) = (2/T0) * trapz(t(1:1+T0/incrm-1), xt(1:1+T0/incrm-1).*cos(k(kk)*w0*t(1:1+T0/incrm-1)), 2);
bk(kk) = (2/T0) * trapz(t(1:1+T0/incrm-1), xt(1:1+T0/incrm-1).*sin(k(kk)*w0*t(1:1+T0/incrm-1)), 2);
end
sumk = 0;
for kk = 1 : size(k,2)
sumk = ??
end
xt_FS = ??
figure;
plot(t, xt, 'LineWidth', 2)
grid on
hold on
plot(t, xt_FS, 'r', 'LineWidth', 2)
xlabel('t')
ylabel('x(t)')
legend('x(t)','FS approximation')
title('Approximated Signal vs. Fourier Series')
Its suppose to build off of the code you previously helped me on of having to create a square wave using 'ones' and 'zeroes'.
clear all; close all; clc;
incrm=0.01; T0=2; w0=pi;
t=0:0.01:10;
xt = ones(1,numel(t));
xt(t>=1 & t<2 | t>=3 & t<4 | t>=5 & t<=6 | t>=7 & t<=8 | t>=9 & t<=10)=0;
a0 = (1/T0) * trapz(t(1:1+T0/incrm), xt(1:1+T0/incrm), 2);
k=1:17;
for kk = 1 : size(k,2)
ak(kk) = (2/T0) * trapz(t(1:1+T0/incrm-1), xt(1:1+T0/incrm-1).*cos(k(kk)*w0*t(1:1+T0/incrm-1)), 2);
bk(kk) = (2/T0) * trapz(t(1:1+T0/incrm-1), xt(1:1+T0/incrm-1).*sin(k(kk)*w0*t(1:1+T0/incrm-1)), 2);
end
sumk = 0;
for kk = 1 : size(k,2)
sumk = ??
end
xt_FS = ??
figure;
plot(t, xt, 'LineWidth', 2)
grid on
hold on
plot(t, xt_FS, 'r', 'LineWidth', 2)
xlabel('t')
ylabel('x(t)')
legend('x(t)','FS approximation')
title('Approximated Signal vs. Fourier Series')
Help you to make your code easier for reading.
What is the error/problem encountering from the code above? Do you mind to elaborate more?
I need help finishing my code. I don't know what to put for sumk or xt_FS. No matter what I plug into my sumk or my xt_FS my plot comes out blank.

Sign in to comment.

Answers (0)

Products

Asked:

on 27 Oct 2018

Edited:

on 7 Mar 2026

Community Treasure Hunt

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

Start Hunting!