power method with euclidean norm in matlab

We can easily use the power method to find the largest eigenvalue of a matrix in MATLAB, and we can also calculate the euclidean norm of a vector using the norm command. Here is how we can combine these two:

main.m
function [lambda, v] = power_method(A, x0, tol, maxiter)
% A: matrix
% x0: initial guess vector
% tol: tolerance for convergence
% maxiter: maximum number of iterations

n = length(x0);
v = x0 / norm(x0);

for k = 1:maxiter
    w = A * v;
    lambda = dot(v, w);
    if norm(w - lambda*v) < tol
        break
    end
    v = w / norm(w);
end
end
346 chars
19 lines

Here, we normalize the initial guess x0 to obtain the initial approximation v. In each iteration of the power method, we calculate the matrix-vector product A*v to obtain a new vector w, and then estimate the eigenvalue by lambda = dot(v,w), where dot is the dot product. We check for convergence using the euclidean norm norm(w - lambda*v), and if the error is below the tolerance tol, we terminate the loop. Otherwise, we normalize the vector w to obtain the next approximation v and continue with the next iteration.

Note that this implementation assumes that A is a square matrix and has a dominant eigenvalue. If A is not diagonalizable or has multiple eigenvalues which are close in magnitude, the power method may not converge or converge slowly. In such cases, it may be necessary to use a different method or modify the power method.

related categories

gistlibby LogSnag