Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.0 kB
3
Indexable
Never
function x = gaussianJordan(A, b)
    [m, n] = size(A);
    if m ~= n
        error('Coefficient matrix must be square.');
    end
    if length(b) ~= m
        error('Dimensions of A and b do not match.');
    end
    
    % Augment the matrix A with the vector b
    Aug = [A, b];
    
    % Perform Gaussian-Jordan elimination
    for k = 1:n
        % Find the pivot row
        [~, pivotRow] = max(abs(Aug(k:end, k)));
        pivotRow = pivotRow + k - 1;
        
        % Swap the current row with the pivot row if necessary
        if pivotRow ~= k
            Aug([k, pivotRow], :) = Aug([pivotRow, k], :);
        end
        
        % Normalize the pivot row
        Aug(k, :) = Aug(k, :) / Aug(k, k);
        
        % Eliminate elements above and below the pivot
        for i = 1:m
            if i ~= k
                factor = Aug(i, k);
                Aug(i, :) = Aug(i, :) - factor * Aug(k, :);
            end
        end
    end
    
    % Extract the solution vector
    x = Aug(:, end);
end
Leave a Comment