Question

I am trying to use forward elimination to row reduce a matrix in Matlab. So far I've been unsuccessful. This the code I have written so far. (It's in the form ax=b)

a = [4 1 -1;5 1 2;6 1 1];
b = [-2 4 6];
width = size(a,2); 
height = size(a,1);
x=1;
y=1;
i=1;

% forward elimination
for i=1 : width
    for y=2 : height
        factor = a(y,x) / a(1,x);
        for x=i : width  
            a(y,x) = a(y,x) - a(1,x) * factor;
        end
        x=1;
    end

end

This produces an ouput like so:

4.0000    1.0000   -1.0000
     0   -0.2500    3.2500
     0   -0.5000    2.5000 

So it's close but I need one more zero in the last row. Can anyone help with figure this out? I'd appreciate it.

Was it helpful?

Solution

I guess you are looking for this:

clear all
close all

a = [4 1 -1;5 1 2;6 1 1];
b = [-2 4 6];
width = size(a,2); 
height = size(a,1);

% forward elimination
for i=1 : width
    for y=i+1 : height
        factor = a(y,i) / a(i,i);
        for x=i : width  
            a(y,x) = a(y,x) - a(i,x) * factor;
        end
    end
end

Note also that if a is not square, i is in {1,...,min(width,height)}. This is going to happen when you make the same operations that you make in a also in b, since a=[a,b] = augumented matrix.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top