ILoveMath
ILoveMath

Reputation: 159

Swapping rows in a row echelon

I'm trying to make a program that computes, given any matrix A, its echelon form. Here is my code:

function A = myrref(A)

[m,n]=size(A);

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

It seems to work almost fine, but I still have a problem when swapping rows. For instance, when trying to get echelon form of matrix A=[1 1 1; 2 2 1; 1 2 2], I obtain [1 1 1; 0.5 1 1; 0 0 -1] which is not what I want. Do I need to add another loop that takes care of the 0.5 in the second row first column?

Upvotes: 0

Views: 824

Answers (2)

user1543042
user1543042

Reputation: 3440

Just as @percusse said you need to finish the loop also your pivot should only go to m-1

Edit: Added an initial pivot based on @AVK's comment

function A = myrref(A)
[m,n]=size(A);

for i = 1:m-1
    if A(i,i) == 0
        row1=A(i,:);
        A(i,:)=A(i+1,:);
        A(i+1,:)=row1;
    end
end

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

    for i = j+1:m-1
        if A(i,i) == 0
            row1=A(i,:);
            A(i,:)=A(i+1,:);
            A(i+1,:)=row1;
        end
    end
end

Upvotes: 1

AVK
AVK

Reputation: 2149

Firstly, it is simplier to use while loop for j because j is not necessarily growing on each iteration. The leading coefficient is not necessarily located on the main diagonal; when all the elements below the leading 0 are zeros, the leading coefficient position shifts to the right.

Secondly, the leading coefficient should be checked before A(j,:)/A(j,j) (to prevent division by 0)

Thirdly, the temporary is not needed to swap the rows as A([i j],:)= A([j i],:) swaps the ith and jth rows of A.

Here is my version of myrref:

function A = myrref(A)
[m,n]=size(A);
j= 1; % the row index of the leading coefficient position
k= 1; % the column index of the leading coefficient position
while j<m && k<=n
    if A(j,k)==0 % we need to change the row order
        zeroindex= find(A(j+1:end,k)~=0); % find nonzero elements below A(j,k)
        if isempty(zeroindex)
            k= k+1; % there is no such elements; shift to the right
        else
                % swap the rows
            A([j zeroindex(1)+j],:)= A([zeroindex(1)+j j],:);
        end
    else
        A(j,:) = A(j,:)/A(j,k);
        for i= j+1:m
            A(i,:)= A(i,:)- A(j,:)*A(i,k);
        end
        j= j+1; k= k+1;
    end    
end

Upvotes: 2

Related Questions