MATLAB: Trying to plot Fourier series, but just getting a straight line?

analysisfourierfunctionplotseries

Hi, i am trying to plot the a fourier series
i have the code below but all i seem to be getting is a straight line? i cannot for the life of me see what is wrong? i should be expecting something like :-
but sll i get is
Could anyone shed any light on this issue please, the code below is run with …….FourierSq(1 , 0.25 , 6)
ie a0=1 , T=0.25 and n=6
the code is meant to plot the first 6 terms of fourier series and the resulting sum of them also on the same plot
function [t,f] = FourierSq(A0,T,n)
t = 0 : T/256 : 4*T;
nn = length(t);
f = zeros(n,nn);
s = zeros(nn);
for ii = 1:n
for j = 1:nn
f(ii) = f(ii,j) + (4*A0/(2*ii-1)*pi) * sin(2*pi*(ii-1)*t(j));
s(j) = s(j) + f(ii,j);
end
end
hold on
for ii = 1:n
plot (t,f(ii,:),'r:')
end
plot(t,s,'k-','linewidth',2)
hold off
end

Best Answer

Replace
f(ii) = f(ii,j) + (4*A0/(2*ii-1)*pi) * sin(2*pi*(ii-1)*t(j));
with
f(ii,j) = f(ii,j) + 4*A0/((2*ii-1)*pi) * sin(2*pi*(2*ii-1)*t(j)/T);