Advertisement
Tachq

Untitled

Nov 19th, 2020
2,603
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Octave 1.61 KB | None | 0 0
  1. name=input('Enter name of input text file : ','s');
  2. %name='in_2';
  3. name=strcat(name,'.txt');
  4. fileid=fopen(name, 'r');
  5. formatspec= '%f';
  6. sizea=inf;
  7. A = fscanf(fileid,formatspec,sizea);
  8. fclose(fileid);
  9. n=A(1);
  10. mat=(reshape(A(2:n*n+1),n,n))';
  11. tol=A(n*n+2);
  12. choose=input('what do you need? (l/a) \nl-largest eigenvalue \na-all eigenvalues \n','s');
  13. if choose=='l'
  14.     [l,v,i]=powme(mat,n,tol)
  15.     fileid=fopen('out_2l.txt','w');
  16.     fprintf(fileid,'Largest eigenvalue \n');
  17.     fprintf(fileid,'%f\n',l);
  18.     fprintf(fileid,'Eigenvectors \n');
  19.     fprintf(fileid,'%f\n',v);
  20.     fprintf(fileid,'No. of iterations\n%d\n',i);
  21.     fprintf(fileid,'\n');
  22.     fclose(fileid);
  23. end
  24.  
  25. if choose=='a'
  26.     [ev,i]=qrev(mat,n,tol)
  27.     fileid=fopen('out_2a.txt','w');
  28.     fprintf(fileid,'Eigenvalues \n');
  29.     fprintf(fileid,'%f\n',ev);
  30.     fprintf(fileid,'No. of iterations\n%d\n',i);
  31.     fclose(fileid);
  32. end
  33.  
  34. function [l,v,i]=powme(mat,n,tol)
  35. z=zeros(n,1);
  36. z(1)=1;
  37. y=z;
  38. i=0;
  39. while 1
  40.     i=i+1;
  41.     y=z/norm(z,2);
  42.     z=mat*y;
  43.     yo=y;
  44.     y=z/norm(z,2);
  45.     z=mat*y;
  46.     if norm(y-yo,Inf)*100<=tol
  47.         break
  48.     end
  49. end
  50. l=(y')*z;
  51. v=y;
  52. end
  53.  
  54. function [ev,ic]=qrev(mat,n,tol)
  55. ic=0;
  56. while 1
  57.     ic=ic+1;
  58.     q=zeros(n,n);
  59.     z=zeros(n,1);
  60.     q(:,1)=mat(:,1)/norm(mat(:,1),2);
  61.     for k=1:n-1
  62.         sum=zeros(n,1);
  63.         for i=1:k
  64.             sum=sum+((mat(:,k+1)')*q(:,i))*q(:,i);
  65.         end
  66.         z=mat(:,k+1)-sum;
  67.         q(:,k+1)=z/norm(z,2);
  68.     end
  69.     r=q'*mat;
  70.     lo=diag(mat);
  71.     mat=r*q;
  72.     l=diag(mat);
  73.     if norm(l-lo,Inf)*100<=tol
  74.         break;
  75.     end
  76. end
  77. ev=l;
  78. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement