Arijeet Dutta
Arijeet Dutta

Reputation: 45

Need to create upper triangular matrix but the loops are not working properly

Hi I am trying to make a matrix upper triangular by using elementary row operations

a = [1 1 0 1;2 1 -1 1;4 -1 -2 2;3 -1 -1 1]

function [c,d,e] = elim(a)
for i = 2:4
    a(i,:) = a(i,:) - a(1,:)*(a(i,1)/a(1,1))
end
c = a

for j=3:4
    c(j,:) = c(j,:) - c(1,:)*(c(j,1)/c(1,1))
end
d = c

for k=4:4
    d(k,:) = d(k,:) - d(1,:)*(d(k,1)/d(1,1))
end

e = d

and the output is

   1   1   0   1
   0  -1  -1  -1
   0  -5  -2  -2
   0  -4  -1  -2

so only the first column has been changed by the first 'for' loop in the code and the rest of the two 'for' loops seem to be not working. Any help?

Upvotes: 1

Views: 738

Answers (3)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

What I love about Matlab is that, for a majority of situations, there is no need to reinvent the wheel:

a = [1 1 0 1;2 1 -1 1;4 -1 -2 2;3 -1 -1 1];
e = tril(a,-1) + triu(a);

Upvotes: 0

Arijeet Dutta
Arijeet Dutta

Reputation: 45

Thanks to Dmitri for the insight; I made a general program as follows

% this program takes input as a square matrix with arguments for 
% function as the matrix itself(a) and the order of the matrix(m)

function [c] = elim_ut_gen(a,m)
for j=1:(m-1)
    for i = (j+1):m
        a(i,:) = a(i,:) - a(j,:)*(a(i,j)/a(j,j))

    end
end

c=a

a =

 1     1     0     1
 2     1    -1     1
 4    -1    -2     2
 3    -1    -1     1


ans =

     1     1     0     1
     0    -1    -1    -1
     0     0     3     3
     0     0     0    -1

Upvotes: 1

Dima Chubarov
Dima Chubarov

Reputation: 17179

There are a few minor mistakes in your function. Below they are fixed

function [c,d,e] = elim(a)
c = a;
for i = 2:4
    c(i,:) = c(i,:) - c(1,:)*(c(i,1)/c(1,1));
end

d = c;
for j=3:4
    d(j,:) = d(j,:) - d(2,:)*(d(j,2)/d(2,2));
end

e = d;
for k=4:4
    e(k,:) = e(k,:) - e(3,:)*(e(k,3)/e(3,3));
end
end

On subsequent steps of elimination you should use the elements of the corresponding row. That is on step two you should use the second row to eliminate elements of the second column, and so on.

The result:

>> [c,d,e] = elim(a)
c =

   1   1   0   1
   0  -1  -1  -1
   0  -5  -2  -2
   0  -4  -1  -2

d =

   1   1   0   1
   0  -1  -1  -1
   0   0   3   3
   0   0   3   2

e =

   1   1   0   1
   0  -1  -1  -1
   0   0   3   3
   0   0   0  -1

There are a few problems remaining:

  1. The function should check if the diagonal element used for elimination is not zero and report an error
  2. The function can easily be generalized to handle matrices of arbitrary shape.

Upvotes: 0

Related Questions