'computing LU factrs of a matrix using partial pivoting and assuming that A is invertible

I am writting a program in MATLAB. It needs to computer LU factors of a matrix using partial pivoting and assuming that A is invertible. I input a square matrix A and my output should be square matrix U containing the LU factors of A. The function below works perfectly but my prof wants me to use the max(abs(vector) instead of if abs(M(k,k)) < abs(M(j,k)) % partial pivoting fuction in matlab to swap necessray rows in the given column. I am not sure how to do that. Any help would be appreciated.

enter code here

function [M, inds] = partialpivotLU(A)

M = A;
[r,c] = size(M);
inds = (1:r);
inds = [inds' inds'];

for k = 1:(c-1)
        ind = [k+1 : r];
    for j = k+1:(r) 
        if abs(M(k,k)) < abs(M(j,k))         % partial pivoting        
            M = swapRow(M, k, j);            % keeping track of index
            inds = swapRow(inds, k, j);            
    end
end
M(ind,k) = M(ind,k)/M(k,k);                % compute multipliers
    for i = ind
        M(i,ind) = M(i,ind) - M(i,k)*M(k,ind); % row reduction
end
end 
     inds = inds(:,1);
end

function [A] = swapRow(A, row1, row2)
%[A] =  swapRow(A, row1, row2)
% Swaps the row 1 for row 2 in a matrix
A([row2,row1], : ) = A ([row1,row2], :);

end

I added the max function and wrote it like :

enter code here
 for j = k+1:(r) 
        pivot=max(abs(M(k:r,k)));
         if (abs(M(j,k))==pivot)        % partial pivoting        
            M = swapRow(M, k, j);            % keeping track of index
            inds = swapRow(inds, k, j);            
        end

my output was

lu(M)

ans =

3.0000    2.0000    1.0000
0.3333    1.3333    2.6667

partialpivotLU(M)

ans =

3.0000    2.0000    1.0000
0.3333    1.3333    3.0000

I dont know what I need to fix.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source