function nma_HW2_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=2
alpha=1;
x=linspace(0,L,100);
len=length(x);
y=x;

ul=0;
ur=1000;

y(1:len/2)=ul;
y(len/2+1:end)=ur;
plot(x,y,'LineWidth',2.5);
hold on;

maxn=1000;
tol=1/10;

for n=1:2:1000
     u0=getApproxInitial(x,L,n,ul,ur);
    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,ul,ur)
u0=zeros(length(x),1)';
for n=1:nTerms
    wn=n*pi/L;
    if x<L
       u0=u0 + 2*ur/(wn*L)*(cos(wn*L)-1)*(sin(n*pi*x/L));
    else
      u0=u0 + ur/wn*(cos(2*wn*L)-cos(wn*L))/(L/2- (1/4*wn)*(cos(4*wn*L)-sin(2*L*wn))) * sin(n*pi*x/L);
    end
end
