function nma_HW1_part2_MAE200B
%function to determine the best n, number of fourier series
%terms to sum to get best fit for u0
close all, clear all;

L=1
alpha=1;
nPoints=100;
x=linspace(0,L,nPoints);
y=x;
len=length(x);
y(1:len/2)=x(1:len/2);
y(len/2+1:end)=L-x(len/2+1:end);
plot(x,y,'LineWidth',2.5);
hold on;
maxn=1000;
tol=1/1000;

for n=1:2:1000
    u0=getApproxInitial(x,L,n);
    diff=sqrt((y-u0).^2);
    maxError=max(diff);
    if maxError<tol
        n
        plot(x,u0,'r');
        break;
    end
end

title('finding number of terms for max error less than 0.1%');
xlabel('x');
ylabel('U(0,x)');

function u0=getApproxInitial(x,L,nTerms)
u0=zeros(length(x),1)';
for n=1:nTerms
    u0=u0 + 4*L*sin(n*pi/2)/(n*pi)^2 * sin(n*pi*x);
end