I've written code for a Fourier series. This is what I have so far:
function FS = FourierSeries(f,degree)
cosCoefficients = zeros(1,degree);
sinCoefficients = zeros(1,degree);
syms x;
a0 = double((1/pi)*int(f,-pi,pi));
for n = 1:degree
cosCoefficients = cosCoefficients + (1/pi)*int(f*cos(n*x),-pi,pi);
sinCoefficients = sinCoefficients + (1/pi)*int(f*sin(n*x),-pi,pi);
end
for n = 1:degree
FS = 0.5*a0 + cosCoefficients.*cos(n*x) + sinCoefficients.*sin(n*x);
end
Then, I've also created the following function file:
function y = func1(x)
syms x
y = (x^2);
end
The problem is that when I try to plot func1
and FS1 = FourierSeries(func1, 4)
, I keep getting an error that says
Data must be numeric, datetime, duration or an array convertible to double.
How do I plot this Fourier series?
whos FS1
Name Size Bytes Class Attributes
FS1 1x4 8 sym
This tells you that FS1
is a symbolic function, which needs to be evaluated before you can plot it:
FS1 = FourierSeries(func1, 4);
xIDX = -10:0.1:10;
array = zeros(size(xIDX));
for ii = 1:numel(xIDX)
x = xIDX(ii);
array(ii) = sum(double(subs(FS1)));
end
figure
plot(array)
subs
converts your symbolic expression to a string, provided that the symbolic variable, x
in this case, is present in the workspace. double
then converts the string to an actual number, and since there's 4 terms in FS
, we need to sum those, that's what a Fourier series is after all.
Even shorter, don't evaluate it numerically, but make use of MATLAB's built-in symbolic plot function fplot
figure
hold on
fplot(func1,'b')
fplot(sum(FS1),'r') % sum over the Fourier components
legend ('func1', 'FS1')