Hi @Egypt,
The provided MATLAB code effectively demonstrates the Fourier series representation of a periodic function, specifically a square wave defined by the function ( f(x) ).
% Define the function f(x) f = @(x) (x > 0 & x < pi) - (x < 0 & x > -pi);
% Define the Fourier series representation fourier_series = @(x) (4/pi) * (sin(x)/1 + sin(3*x)/3 + sin(5*x)/5 + sin(7*x)/7);
% Define the range for x x = linspace(-pi, pi, 1000);
% Calculate the function values and Fourier series values f_values = f(x); fourier_values = fourier_series(x);
% Plotting the results figure; plot(x, f_values, 'r', 'LineWidth', 2); % Original function hold on; plot(x, fourier_values, 'b', 'LineWidth', 2); % Fourier series hold off;
% Adding labels and title
xlabel('x');
ylabel('f(x) and Fourier Series');
title('Fourier Series Representation of f(x)');
legend('f(x)', 'Fourier Series', 'Location', 'Best');
grid on;
Please see attached.


The function is defined as ( f(x) = 1 ) for ( 0 < x < pi ) and ( f(x) = -1 ) for ( -pi < x < 0 ). The Fourier series approximation is constructed using the first four odd harmonics of sine functions.
Function Definition: The function ( f(x) ) is defined using an anonymous function, which allows for concise representation and evaluation over a range of ( x ) values.
Fourier Series Calculation: The Fourier series is computed by summing the first four terms of the sine series, scaled by their respective coefficients. This is encapsulated in another anonymous function.
Plotting: The code generates a range of ( x ) values from (-pi) to (pi) and computes both the original function and its Fourier series values. The results are plotted on the same graph, with distinct colors for clarity.
This code serves as a practical example of how Fourier series can approximate complex periodic functions, which is essential in signal processing, acoustics, and electrical engineering. By visualizing the original function alongside its Fourier series, one can observe how the series converges to the function as more terms are added, illustrating the power of Fourier analysis in practical applications.
Please let me know if you have any further questions.
