Untitled

 avatar
unknown
plain_text
a year ago
1.5 kB
4
Indexable
% Gaussian Elimination method
C = [1 2 -1; 2 1 -2; -3 1 1];
b = [3; 3; -6];

% Augmented matrix
A = [C, b];

n = size(A, 1); % Number of equations/variables
x = zeros(n, 1); % Variable matrix [x1; x2; x3]

for i = 1:n-1
    for j = i+1:n
        m = A(j, i) / A(i, i);
        A(j, :) = A(j, :) - m * A(i, :);
    end
end

% Back substitution
x(n) = A(n, n+1) / A(n, n);
for i = n-1:-1:1
    summ = 0;
    for j = i+1:n
        summ = summ + A(i, j) * x(j);
    end
    x(i) = (A(i, n+1) - summ) / A(i, i);
end

disp('Solution:');
disp(x);


number 3:\



%A= input('Please Enter the size of the equation system A=  ') ;
%b = input('Please Enter the elements of the Matrix b =' ) ;
%x0= input('Please Enter the elements of the Matrix x0 =' ) ;
%max_iter= input('Please Enter the elements of the Matrix max_iter=' ) ;

A = [4 1 3; 1 5 1; 2 -1 8];
b = [17; 14; 12];

x0 = [0; 0; 0];

max_iter = 100;

tol = 1e-6;

x = x0;

x_prev = x0;

[n, ~] = size(A);

iter = 0;

while iter < max_iter

    for i = 1:n
        sigma = 0;
        for j = 1:n
            if j ~= i
                sigma = sigma + A(i, j) * x_prev(j);
            end
        end
        x(i) = (b(i) - sigma) / A(i, i);
    end
    

    if norm(x - x_prev) < tol
        break;
    end
    
    x_prev = x;
    
    iter = iter + 1;
end


if iter == max_iter
    disp('Maximum number of iterations reached without convergence');
else
    disp('Solution:');
    disp(x);
    disp(['Number of iterations: ', num2str(iter)]);
end
Editor is loading...
Leave a Comment