how to jacobi in matlab

Jacobi Method is an iterative algorithm for solving linear system of equations. Here is an implementation of Jacobi method in Matlab:

main.m
function [x, num_iter] = jacobi(A, b, x0, tol, max_iter)
% Solves linear system of equations Ax = b using Jacobi Method

% Input:
%   - A: matrix
%   - b: vector
%   - x0: initial guess (default: zero vector)
%   - tol: tolerance (default: 1e-6)
%   - max_iter: maximum number of iterations (default: 1e3)

% Output:
%   - x: solution vector
%   - num_iter: number of iterations required to converge

% Set default values if not provided
if nargin < 5
    max_iter = 1e3;
end

if nargin < 4
    tol = 1e-6;
end

if nargin < 3
    x0 = zeros(size(A, 1), 1);
end

% Initialize variables
x = x0;
num_iter = 0;
norm_residual = inf;

% Jacobi iteration
while norm_residual > tol && num_iter < max_iter
    x_new = x;
    for i = 1:size(A, 1)
        sigma = 0;
        for j = 1:size(A, 2)
            if i ~= j
                sigma = sigma + A(i, j) * x(j);
            end
        end
        x_new(i) = (b(i) - sigma) / A(i, i);
    end
    norm_residual = norm(A * x_new - b, 2);
    x = x_new;
    num_iter = num_iter + 1;
end

% Check convergence
if norm_residual > tol
    warning('Jacobi Method did not converge');
end

end
1128 chars
56 lines

To use the above function, you can simply call it with the input parameters:

main.m
A = [2 -1 0; -1 2 -1; 0 -1 2];
b = [1; 0; 1];
x0 = [0; 0; 0];
tol = 1e-6;
max_iter = 1e3;
[x, num_iter] = jacobi(A, b, x0, tol, max_iter);
139 chars
7 lines

This will solve the linear system of equations Ax = b using Jacobi Method with initial guess x0, tolerance tol, and maximum number of iterations max_iter. The solution vector x and number of iterations required to converge num_iter will be returned.

related categories

gistlibby LogSnag