title: Power Method in MATLAB
body: <p>I would like to implement the <a href="http://mathfaculty.fullerton.edu/mathews//n2003/PowerMethodMod.html" rel="nofollow">Power Method</a> for determining the dominant eigenvalue and eigenvector of a matrix in MATLAB.</p>
  
  <p>Here's what I wrote so far:</p>
  
  <pre><code>%function to implement power method to compute dominant
  %eigenvalue/eigenevctor
  function [m,y_final]=power_method(A,x);
  m=0;
  n=length(x);
  y_final=zeros(n,1);
  y_final=x;
  tol=1e-3;
  while(1)
      mold=m;
   y_final=A*y_final;
   m=max(y_final);
   y_final=y_final/m;
   if (m-mold)&lt;tol
       break;
   end
  end
  end
  </code></pre>
  
  <p>With the above code, here is a numerical example:</p>
  
  <pre><code> A=[1 1 -2;-1 2 1; 0 1 -1]
  
  A =
  
       1     1    -2
      -1     2     1
       0     1    -1
  
  &gt;&gt; x=[1 1 1];
  &gt;&gt; x=x';
  &gt;&gt; [m,y_final]=power_method(A,x);
  &gt;&gt; A*x
  
  ans =
  
       0
       2
       0
  </code></pre>
  
  <p>When comparing with the eigenvalues and eigenvectors of the above matrix in MATLAB, I did:</p>
  
  <pre><code>[V,D]=eig(A)
  
  V =
  
      0.3015   -0.8018    0.7071
      0.9045   -0.5345    0.0000
      0.3015   -0.2673    0.7071
  
  
  D =
  
      2.0000         0         0
           0    1.0000         0
           0         0   -1.0000
  </code></pre>
  
  <p>The eigenvalue coincides, but the eigenvector should be approaching <code>[1/3 1 1/3]</code>.  Here, I get:</p>
  
  <pre><code> y_final
  
  y_final =
  
      0.5000
      1.0000
      0.5000
  </code></pre>
  
  <p>Is this acceptable to see this inaccuracy, or am I making some mistake? </p>