graphics_toolkit("gnuplot")


%creating a tridiagonal symmetric matrix with 2 on the main diagonal and -1 on subdiagonal 

%using diag
N=10;
function A=trid1(N)
 d=ones(N,1);
 A=2*diag(d)-diag(d(1:N-1),1)-diag(d(1:N-1),-1);
end
A1=trid1(7)
%using loop
function A=trid2(N)
 B4=[2 -1;-1 2];
 for k=1:N-1,
   A(k:k+1,k:k+1)=B4; 
 end  
end
A2=trid2(7)

%sparse using sparse(I,J,S,N,N)
function A=sptrid1(N)
 d=ones(1,N);
 I=[1:N,2:N,1:N-1];
 J=[1:N,1:N-1,2:N];
 S=[2*d,-d(1:N-1),-d(1:N-1)];
 A=sparse(I,J,S,N,N);
end
A3=sptrid1(7);
full(A3)


%sparse using spdiags(V,D,N,N)
function A=sptrid2(N)
 d=ones(1,N)';
 V=[2*d,-d,-d];
 D=[0,1,-1];
 A=spdiags(V,D,N,N);
end
A4=sptrid2(7);
full(A4)

%comparing time for full functions
N=10;
M=5;
t=zeros(M,4);
for k=1:M,
 if(k<=3) 
  tic;trid1(N);t(k,1)=toc;
  tic;trid2(N);t(k,2)=toc;
 end 
 tic;sptrid1(N);t(k,3)=toc;
 tic;sptrid2(N);t(k,4)=toc;
 N*=10;
end
format long e
tc=t

%comparing time fo solving the system with A for 2 methods:
%backslash - multiplying by the precomputerd inv(A)

%comparing time for full functions
N=10;
M=6;
t=zeros(M,5);
for k=1:M,
 b=randn(N,1); 
 t(k,1)=N;
 if(k<=5) 
  A=trid1(N);
  tic;A\b;   time1=t(k,2)=toc; time1;
  B=inv(A);
  tic;B*b;   time2=t(k,3)=toc; time2;
 end 
  A=sptrid1(N);
  tic;A\b; sptim1=t(k,4)=toc; sptim1;
  B=inv(A);
  tic;B*b; sptime2=t(k,5)=toc;sptime2;
  N*=3;
end
ts=t

format short


%element by a element comparison plot a graph 1+max(f,g)
%not using a loop

f=@sin;
g=@cos;
a=-4*pi;b=5*pi;
x=linspace(a,b,800);
plot(x,y=1+max([f(x);g(x)]),"b;1+max(s,c);",x,f(x),"g;s;",x,g(x),"r;c;")
pause(3);
x=linspace(-2,4,300);
y=cos(x);y=(y>0).*y;
plot(x,y,";max(cos,0);")